0

How to take input from console in a loop ?

Let us suppose node promt asks how many students are in a class? after this user enter 5, then there should be a promt asking 5 times "enter their name one by one", and all name has to be stored in an array

1
  • Something like prompt would work for this.. (has more than double the amount of weekly downloads on NPM versus readline-sync).. Commented Sep 15, 2019 at 16:26

2 Answers 2

1

Try this

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

let n;
let array = []

function mainfunction() {
    if( n == array.length){
        console.log("your output: ",  array)
        rl.close()
    }
    else{
        rl.question('enter student name one by one \n', (name) => {
            array.push(name)
            mainfunction()
        })
    }
 }

rl.question('enter the number of students ', (answer) => {
    n = answer
    mainfunction()
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can do something like this with the readline-sync package

 var readline = require('readline-sync');

    let num = readline.question("how many students are in a class ?");
    let names=[];
    for(let i=0;i<=num;i++)
    {
      let name = readline.question("Enter Name?");
      names.push(name);
    }
    console.log(names);

Working repl-https://repl.it/repls/LightyellowEvenBusinesses

2 Comments

can it work in online challenges problem, like hackers earth etc etc
It should ,I guess try it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.