🧡How to take input in javascript using console (codechef)

aryan015

aryan015

Posted on July 27, 2024

🧡How to take input in javascript using console (codechef)

You might have always struggled with javascript to take input from console. I also encountered such situations in competitive programming. You don't have such function in JS but node.js. We will take use of input stream(stdin). Remember that everything received from console considered as a string even numbers.

process.stdin.setEncoding('utf8'); // it sets the encoding
// try this snippet without setting encoding (homework)
process.stdin.on('data',function(input){
  console.log(input) // your output
})
Enter fullscreen mode Exit fullscreen mode

note:It is a pain🍑 in javascript to take input🤷‍♀️. You might need on-the-go ready snippet in competitive programming.

input

// add this number and return the result
//10 11 12
process.stdin.setEncoding('utf8');
process.stdin.on('data',function(input){
  let strArray = input.split(" "); // ['10','11','12']
// Convert each string to a number and sum them up
let sum = strArray.reduce((acc, num) => acc + Number(num), 0);
console.log(sum) // whatever the sum is
})
Enter fullscreen mode Exit fullscreen mode

output

33
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
aryan015
aryan015

Posted on July 27, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related