[英]Separate scanf input with space in C
I try to input a series of numbers, every number separated by a space. 我尝试输入一系列数字,每个数字用空格分隔。 The series of numbers has to stop taking input once a
0
is given. 一旦给出
0
该系列数字必须停止输入。
I do this with a for
loop. 我用
for
循环做这个。 If I separate every number with \\n
, it stops indeed reading input after I have given 0
as a number. 如果我用
\\n
分隔每个数字,它在我给出0
作为数字后确实停止读取输入。
But if I instead separate every number with a space, nothing happens after I give a 0
. 但是,如果我用空格分隔每个数字,那么在给出
0
后没有任何反应。 It just keeps reading input. 它只是继续阅读输入。
I tried to find an answer, I'm sorry if the solution is obvious. 我试图找到答案,如果解决方案很明显,我很抱歉。 I just started in C, please bear with me..
我刚开始用C,请耐心等待..
int main(int argc, char **argv){
int ar[1000];
int i;
printf("Give a series of numbers, separated by space. Stop reading when `input is 0.\n --> : ");`
for (i = 0; i < SIZE ; i++){
scanf("%d", &ar[i]);
if (ar[i] == 0){break;}
}
return 0;
}
By default, most command-line terminals will only send input to the running program after you finish typing a whole line. 默认情况下,大多数命令行终端只会在完成整行输入后向正在运行的程序发送输入。 This is to give you a chance to fix typos with the backspace key.
这是为了让您有机会使用退格键修复拼写错误。
One easy solution is to, instead of typing the input by hand, put it in a text file and use file input redirection ( <
). 一个简单的解决方案是,不是手动输入输入,而是将其放在文本文件中并使用文件输入重定向(
<
)。 This input redirection syntax works on both Linux and Windows shells. 此输入重定向语法适用于Linux和Windows shell。
myProgram.exe < myInput.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.