阅读空间分隔的数字使用scanf函数并将其存储在一个数组 - Ç [英] Read in space delimited numbers using scanf and storing them in an array - C
问题描述
我试图服用含有一堆空格分隔使用scanf的1-3位数(),并将它们存储到一个int数组并打印在新的行测试每个单独的一个用户输入,但它不工作。以下是我迄今为止:
I'm trying to take user input containing a bunch of space delimited 1-3 digit numbers using scanf() and storing them into an int array and printing each seperate one on a new line to test but it's not working. Here is what I have so far:
#include <stdio.h>
#include <string.h>
int main()
{
int sourceArr[500];
int i = 0;
printf("\nEnter ciphertext: \n");
while (scanf("%d", &sourceArr[i++]) == 1);
for (int j=0;j<500;j++) {
printf("%d\n", sourceArr[j]);
}
}
所以要求用户输入一个数字序列,像这样:
so the user is asked to input a sequence of numbers like so:
Enter ciphertext:
23 122 32
和我想在sourceArr [0],122存储23 sourceArr [1],并在sourceArr 32 [2],然后打印每一个像这样:
and I want to store 23 in sourceArr[0], 122 in sourceArr[1] and 32 in sourceArr[2] and then print each one like so:
23
122
32
但该程序进入空闲后输入正确的,并不会打印编号。
But the program idles right after entering the input and won't print the numbers.
推荐答案
在成功的 scanf函数返回参数列表中的项目成功填补数。该计数可以匹配项的预期数量或更少(甚至为零)由于匹配失败,读取错误,或者结束文件的范围。
On success, scanf returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.
您可以将其更改为:
#include <stdio.h>
#include <string.h>
int main()
{
int sourceArr[500];
int i = 0;
printf("\nEnter ciphertext: \n");
while (scanf("%d", &sourceArr[i++]) == 1);
for (int j=0;j<i-1;j++) {
printf("%d\n", sourceArr[j]);
}
}
然后,如果你输入:
1 2 3 4 5 6×(和回车)
Then if you enter: 1 2 3 4 5 6 x (and hit enter)
它会显示你想要的。
如果你不喜欢的X,你可以使用这个而行:
If you don't like the 'x' you could use this while line:
while (scanf("%d", &sourceArr[i++]) != EOF);
然后键入类似:
12 23 345 554(按回车键),然后在窗口中UNIX(CTRL + Z)或(CTRL + D)
and then type something like: 12 23 345 554 (hit enter) and then (ctrl+z) in windows or (ctrl+d) in unix.
看到这个线程:标准输入的文件(EOF)的结束流(标准输入)
see this thread: End of File(EOF) of Standard input stream (stdin)
CTRL + Z明确,使scanf函数返回EOF,因为控制台没有EOF,需要这种方式进行发送。
ctrl+z explicitly makes scanf return EOF because the console has no EOF and needs to be sent this way.
这篇关于阅读空间分隔的数字使用scanf函数并将其存储在一个数组 - Ç的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!