0

I am able to push the first integer element in the array. After that it takes every input values as a NaN.

How can we remove blank spaces in the array input at runtime. As Ryan said readLine is returning something that isn't parseable as an integer.

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////


function main() {


    var n = parseInt(readLine());

    var a = [];



        for(var i=0;i<n;i++)
        {
         /*I am able to get first input but not for next iteration input value taken as NaN*/
         var no = parseInt(readLine(),10);

         console.log(readLine())


           a.push(no);



        }







}

For example,

input: 1 2 3 4 5

output: 1 NaN NaN NaN NaN

15
  • What readLine() does? Commented Apr 12, 2017 at 7:16
  • I was asking about parseInt(readLine(), 10); Commented Apr 12, 2017 at 7:18
  • @DineshSonachalam Show us the implementation of readLine() Commented Apr 12, 2017 at 7:18
  • 2
    readLine is returning something that isn't parseable as an integer. console.log(readLine()) to find out what. Commented Apr 12, 2017 at 7:20
  • 1
    @Dinesh Sonachalam input_stdin_array = input_stdin.split(" "); add this on your process.stdin.on('end', function () { method instead of your statement it will solve your issue. Commented Apr 12, 2017 at 9:06

1 Answer 1

1

Based on the given input 1 2 3 4 5, it will fail because there is whitespace between the numbers. parseInt returns NaN for any input other than a number.

You can try that out yourself:

parseInt('1 2 3 4 5', 10) // returns 1
parseInt('12345', 10) // returns 12345

You can read more about it (and alternatives to parseInt) here: https://coderwall.com/p/5tlhmw/converting-strings-to-number-in-javascript-pitfalls

What you could do is validate the input and strip out all the slashes:

"1 2 3 4 5".replace(/\s/g, ""); // "12345"

This will make your function handle a numeric input very well while failing with other inputs. It reads like your function should handle every kind of input, instead of using RegEx to filter out stuff like spaces (and, as the old adage goes, you now have two problems)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.