问题
I saw this for lots of other languages but not JavaScript.
I'm trying to do problems like: this (codechef.com) and of course the programs need to be able to read standard in like C++ and other languages do.
EDIT: Thanks for the answers. The primary reason I want this functionality is so I can answer the questions on CodeChef; Codechef sends multiple inputs to the files/programs that are the answers (and of course the programs have to respond in the required way for the answer to be correct).
回答1:
It depends on the environment that your JavaScript is executing in.
In the browser, there is no standard input (the browser isn't a console). The input would come generally from some textbox element in a form on the page.
If you're using something like Rhino, then you can import the standard Java I/O classes and read from stdin that way (see the second example no longer on the wiki).
回答2:
If you use node to act as an interpreter in the terminal, you can use this:
---- name.js ----
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question(">>What's your name? ", function(answer) {
console.log("Hello " + answer);
rl.close();
});
----- terminal ----
node name.js
回答3:
Use just readline()
var a = readLine();
the value which you give input will be stored in variable a.
readline() : Reads a single line of input from stdin, returning it to the caller. You can use this to create interactive shell programs in JavaScript.
回答4:
It's not in the ECMAScript (standardized version of JavaScript) standard library. However, some implementations of JavaScript do include it. For example, CommonJS, which is used by several out-of-the-browser JavaScript environments, has a system.stdin property. Rhino can use Java's standard input classes.
If you're just trying to practice programming, you can use a textarea as a substitute for standard input.
回答5:
In some environments like interviewstreet's, they provide you with a function in which all the input is coming as an argument in form of a string.
All of the input at once.
Then you have to parse that input to get various tokens out of that string.
After this you should be good to write the code further.
来源:https://stackoverflow.com/questions/5396020/is-there-a-way-to-read-standard-input-with-javascript