![](/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.