You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js实现SPOJ PTEST两整数求和程序:标准输入读取问题排查

Fixing Node.js Code for SPOJ PTEST Problem

Let's break down why your two attempts aren't working and fix them to meet the problem's requirements.

Issues with Your First Attempt

  • The rl.question() method prints the prompt strings ("A ? " and "B ?\n") to the output. Online judges like SPOJ expect only the final sum as output—these extra prompts will be flagged as incorrect output, causing your submission to fail.
  • The judge provides input as two raw lines of numbers, not in response to interactive prompts. Your code's flow of waiting for a prompt before reading input doesn't align with how the judge feeds data, leading to potential input mismatches.

Issues with Your Second Attempt

  • The readline.question() function’s callback only accepts one argument (the single line of input entered). Trying to use A, B as parameters is invalid syntax here—this will throw an error. Even if it didn’t, this approach only reads one line of input, but you need two to solve the problem.

Correct Implementation

We need to read two lines of input silently (no prompts), parse them as integers, sum them, and output only the result. Here’s a reliable approach using the line event to capture input:

const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false // Optimizes for automated judge input
});

const inputLines = [];
rl.on("line", (line) => {
  inputLines.push(line.trim());
  // Calculate sum once we have both input lines
  if (inputLines.length === 2) {
    const numA = parseInt(inputLines[0], 10);
    const numB = parseInt(inputLines[1], 10);
    console.log(numA + numB);
    rl.close();
  }
});

Key Reasons This Works:

  • terminal: false configures readline for non-interactive input (like from a judge), avoiding edge cases with interactive terminal behavior.
  • We listen for each line of input, storing them in an array until we have both numbers.
  • Using parseInt with base 10 ensures we correctly parse decimal numbers (prevents unexpected octal parsing if input starts with 0).
  • We only output the sum—no extra text or prompts, exactly what the judge expects.

If you prefer an async/await style, here’s an alternative:

const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

async function calculateSum() {
  const inputLines = [];
  for await (const line of rl) {
    inputLines.push(line.trim());
    if (inputLines.length === 2) break;
  }
  console.log(parseInt(inputLines[0], 10) + parseInt(inputLines[1], 10));
  rl.close();
}

calculateSum();

内容的提问来源于stack exchange,提问作者Andrzej Hnatiuk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 18:17:39