Javascript nodejs中的C扫描等效
如果我想在C中读取输入流,我写Javascript nodejs中的C扫描等效,javascript,node.js,Javascript,Node.js,如果我想在C中读取输入流,我写scanf,在NodeJS中是否有相同的方法 例如,下面是C int n, m, i; scanf("%d", &n); for (i = 0; i < n; i++) { scanf("%d", &m); ............ } intn, M 我 scanf(“%d”和“&n”); 对于(i=0;i
scanf
,在NodeJS中是否有相同的方法
例如,下面是C
int n,
m,
i;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &m);
............
}
intn,
M
我
scanf(“%d”和“&n”);
对于(i=0;i
这是我在Node中开始的地方。。。TODO表示我被卡住的地方:
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) {
var n = +input;
for (var i = 0; i < n; i++) {
// TODO
}
});
process.stdin.resume();
process.stdin.setEncoding(“ascii”);
进程标准开启(“数据”,功能(输入){
var n=+输入;
对于(变量i=0;i
对于初学者来说,在NodeJS中为可读流调用scanf
和data
事件是不等效的。在NodeJS示例中,您将需要解析接收到的输入块
通过将on方法的主体替换为一个简单的:
process.stdout.write('onData: ' + input + '\n');
鉴于input
如何包含数据,您需要使用某种方法提取感兴趣的字符串,然后使用parseInt
。对于您的问题,假设每个输入1个整数,这可能是一种天真的方法:
var n = 0;
var m = 0;
var state = 0;
process.stdin.on('data', function (input) {
switch (state)
{
case 0:
// we're reading 'n'
n = parseInt(input.trim(), 10);
state++;
break;
default:
// we're reading 'm'
m = parseInt(input.trim(), 10);
if (state++ == n)
{
// we've read every 'm'
process.exit();
}
break;
}
});
我不太喜欢这种将数据获取到NodeJS事件循环的方法,相反,您应该查看命令行参数、配置/输入文件或其他方法。此函数将满足您的要求:
function readNums(s) {
// Split it up into numbers and spaces
var array = s.split(/(\d+)/);
// Keep just the numbers
array = array.filter(function(i) {return "" + +i == i});
// Convert back to a number
array = array.map(function(i) {return +i});
// How many elements should there have been?
var maxLen = array.shift();
if (array.length < maxLen) {
throw "Not enough enough numbers";
} else {
array.length = maxLen;
}
return array;
}
console.log(readNums("4 10 20 30 40 50 60 70"));
检查
[10, 20, 30, 40]
var sget = require('./sget');
var width = sget('Width?'),
height = sget('Height?'),
area = width * height;
console.log('Area is', area);