[英]Javascript (Node.js) - How to read and process multiple line provided as an input to a function?
I am practicing to code in various languages and hence, am a newbie to node.js.我正在练习用各种语言编写代码,因此,我是 node.js 的新手。 The site I am using to practice the code mostly gives me multi-line inputs as an argument to my function, which I don't know how to process (I tried using split on \\n, but, that, doesn't work).
我用来练习代码的站点主要为我提供多行输入作为我函数的参数,我不知道如何处理(我尝试在 \\n 上使用 split,但是,那不起作用) .
Following is a code that, gets multi-line input and then, this input is passed to a function.以下是获取多行输入然后将此输入传递给函数的代码。 Can you please tell me how can I read/process the input in-order to store each line of an input in an array as a data item ?
您能告诉我如何读取/处理输入以便将输入的每一行作为数据项存储在数组中吗?
function main(input) {
//Enter your code here
// var arr = input.split("")
process.stdout.write(input[6]);
}
process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";
process.stdin.on("data", function (input) {
stdin_input += input;
});
process.stdin.on("end", function () {
main(stdin_input);
});
Thanks'谢谢'
Splitting on a new line works for me. 拆分新线路对我有用。
function main(input) {
//Enter your code here
var arr = input.split("\n")
process.stdout.write(JSON.stringify(arr));
}
process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";
process.stdin.on("data", function (input) {
stdin_input += input;
});
process.stdin.on("end", function () {
main(stdin_input);
});
It's important to note that process.stdout.write
can only write a string. 重要的是要注意
process.stdout.write
只能写一个字符串。 Trying to pass an array as an argument will cause an error. 尝试将数组作为参数传递将导致错误。
just a idea my code is just for many string or number have space between for example if you want sum two number we write in terminal : 23 56只是一个想法,我的代码仅适用于许多字符串或数字之间有空格,例如,如果您想对我们在终端中写入的两个数字求和:23 56
notice i use here string_decoder for any one want to raplace number with string
请注意,我在这里使用 string_decoder 来表示任何想用字符串替换数字的人
const {StringDecoder} = require('string_decoder');
const decode = new StringDecoder('utf8');
const sum = (a, b) => {
let operation = a + b;
return console.log('result is : ', operation);
}
process.stdin.on('readable', () => {
const aa = process.stdin.read(); // read string from REPL
const buffer = Buffer.from(aa);
const j = decode.write(buffer).split(' ');
const a = +j[0];
const b = +j[1];
// console.log(a + b)
if((a & b) != null) // check if the value not empty
{
sum(a, b);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.