数字.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14
例如,我有上面的文本文件。我想获取文件中整数的数量(在本例中为 14),并将每个整数传递到一个数组中。
我做的是
int count = 0;
int i = 0;
while ( 1 )
{
int c = fgetc( fp );
if ( c == EOF || c == '\n' )
{
if ( c == EOF ) break;
}
else if(c ==' ')
{
++count;
--count;
}
else
{
++count;
arr[i] = c-48; // This line give me the wrong number so I subtract it by 48
++i;
}
}
在这种情况下,只有当文件中没有两位数(例如 10 11 12 13)时,计数才会得到正确的值。否则,它不起作用。
我还尝试使用 fscanf 将每个整数存储在一个数组中,然后获取数组的长度。这是行不通的,因为我必须先定义数组的长度,但我无法做到这一点。
我的问题是如何处理文件中的两位数以获得正确的值。有更好的办法吗?有人可以帮忙吗?提前致谢。
最佳答案
您可以使用 fscanf()
读取整数,每次找到一个数字时,增加一个计数器。
像这样简单的东西可以工作:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fp;
int num;
size_t count = 0;
fp = fopen("somenumbers.txt", "r");
if (!fp) {
fprintf(stderr, "Error reading file\n");
return 1;
}
while (fscanf(fp, "%d", &num) == 1) {
count++;
}
printf("number of digits = %zu\n", count);
fclose(fp);
return 0;
}
关于c - 如何获取其中有空白空间的文件中的整数数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42080418/