Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

javascript - NodeJS - Read two numbers from input stream and print its sum to output stream

I'm trying to solve a task that reads: "Two whole numbers are defined in the standard input stream; each number is >= -32000 and <= 32000. Print the sum of these numbers to the standard output stream." Input:

1
2

Output:

3

My code is below:

let total = 0;
let numbers_counter = 0;
process.stdin.on('data', data => {
    numbers_counter++;
    total += parseInt(data);
    if (numbers_counter == 2) {
        process.stdout.write(total.toString(), () => {
            return process.exit()
        });    
    }   
})
process.stdin.on('end', () => {
    process.stdout.write(total.toString(), () => {
        return process.exit()
    });
})

The problem is that I'm getting a 'wrong answer' response (I don't know how my code is tested, the only output I see is 'wrong answer')

Any clue what needs to be changed?

question from:https://stackoverflow.com/questions/65885262/nodejs-read-two-numbers-from-input-stream-and-print-its-sum-to-output-stream

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To begin with, this is enough:

let total = 0;
let numbers_counter = 0;
process.stdin.on('data', data => {
    numbers_counter++;
    total += parseInt(data);
    if (numbers_counter == 2) {
        process.stdout.write(total.toString(), () => {
            return process.exit()
        });    
    }   
})

And I think this is simpler:

let total = 0;
let numbers_counter = 0;
process.stdin.on('data', data => {
    numbers_counter++;
    total += parseInt(data);
    if (numbers_counter == 2) {
        process.stdout.write(total.toString());
        process.exit();   
    }   
})

Perhaps you will pass if you don't exit the process?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...