![](/img/trans.png)
[英]TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array
[英]TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type number
我正在尝试解决 HackerEarth 中的一个问题。 我正在使用 javascript。下面是我的代码。
// Sample code to perform I/O:
process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";
process.stdin.on("data", function (input) {
stdin_input += input; // Reading input from STDIN
});
process.stdin.on("end", function () {
main(stdin_input);
});
// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
// Write your code here
function main(input) {
var data = input.split('\n');
var a = parseInt(data[0]);
var b = parseInt(data[1]);
var sum = a + b;
process.stdout.write(sum);
}
每当我编译这个时,我都会收到以下错误
Execution failed.
Stack Trace:
events.js:174
throw er; // Unhandled 'error' event
^
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type number
at validChunk (_stream_writable.js:258:10)
at SyncWriteStream.Writable.write (_stream_writable.js:292:21)
at main (/hackerearth/JAVASCRIPT_NODE_3789_1f3d_d89e_d4f9/s_d3fb_2843_f025_60ef.njs:28:16)
at ReadStream.<anonymous> (/hackerearth/JAVASCRIPT_NODE_3789_1f3d_d89e_d4f9/s_d3fb_2843_f025_60ef.njs:13:4)
at ReadStream.emit (events.js:194:15)
at endReadableNT (_stream_readable.js:1125:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
at validChunk (_stream_writable.js:261:12)
at SyncWriteStream.Writable.write (_stream_writable.js:292:21)
[... lines matching original stack trace ...]
at process._tickCallback (internal/process/next_tick.js:63:19)
每当我尝试将输入字符串转换为 integer 时,我都会收到上述错误。 我根本无法对输入数据进行任何算术运算。 如果有任何建议,请告诉我...
我试过 process.stdout.write(""+sum); 它对我有用。
这个问题好像是参考HackerEarth的基本I/O教程问的: https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/tutorial/
请记住, input
包含整个字符串——而不是像使用 C 的scanf()
那样的“逐行”输入。
您根据换行符拆分输入。 没关系。 但是随后您只是将它们转换为int
并加入它们并尝试打印它们。
问题在于“helloworld”不是 integer。如果您尝试将其解析为一个,它会给出NaN
。 将其添加到前10
也会得到NaN
,您将遇到问题。
相反,做这样的事情:
function main(input) {
let inputParts = input.split('\n');
let num = parseInt(inputParts[0]);
inputParts[0] = (num * 2).toString(); // inputParts is now ["10", "helloworld"]
process.stdout.write(inputParts.join('\n'));
}
我们只解析应该解析的部分,把output转回字符串再打印出来。
注意:第 3 行的.toString()
是可选的 - 因为当我们连接数字和字符串时,output 是一个字符串。 为了安全起见,我将其转换为字符串,但是否要这样做取决于您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.