如何从文件中扫描数字到数组? [英] How do I scan in numbers to an array from a file?
问题描述
说我有一个带有数字的文件: 1 2 3 4 5 6 7 8 9 10 -1
Say I have a file with the numbers: 1 2 3 4 5 6 7 8 9 10 -1
我想读入该文件并存储该文件的所有值,并在控制变量-1处停止.
I want to read in that file and store all the values of that file, stopping at the control variable -1.
因此,如果我将该数组打印到另一个文件,它将看起来像: 1 2 3 4 5 6 7 8 9 10
So if I printed that array to another file it would look like: 1 2 3 4 5 6 7 8 9 10
这给了我所有数字,但其中包括-1.我该如何放弃-1?
This gives me all the numbers, but it has -1 included. How can I drop off the -1?
int arr[100];
int n;
while (scanf("%d",&arr[n]) > 0)
n++;
推荐答案
您不能添加> 0
条件:这将给您带来不确定的行为.为了忽略负数,您可以在读取数字后在循环内添加单独的检查,如下所示:
You cannot add the > 0
condition: this would give you undefined behavior. In order to ignore the negative one, you could add a separate check inside the loop, after reading the number, like this:
while (scanf("%d", &arr[n]) != EOF) {
if (arr[n] > 0) {
n++;
}
}
由于数组arr
具有固定大小,因此最好防止出现超限,如下所示:
Since the array arr
has fixed size, it would be a good idea to guard against overruns, like this:
while (n < 100 && scanf("%d", &arr[n]) != EOF) {
if (arr[n] > 0) {
n++;
}
}
如果文件结束前达到100,此循环将停止.请注意,您还需要在循环之前将n
初始化为零,以避免未定义的行为.
This loop would stop if you reach 100 before the file ends. Note that you also need to initialize n
to zero before the loop to avoid undefined behavior.
这是关于ideone的演示.
这篇关于如何从文件中扫描数字到数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!