所以我有一个名为“score.txt”的文件,其中包含内容
NAME
20
NAME2
2
我正在使用这段代码,但它出现错误,而且我不知道如何将文件中的整数放入数组中。
int main(){
FILE* file = fopen ("score.txt", "r");
int i = 0;
fscanf (file, "%d", &i);
while (!feof (file))
{
printf ("%d ", i);
fscanf (file, "%d", &i);
}
fclose (file);
system("pause");
}
我只是自学,我已经尝试解决这个问题两个小时了
最佳答案
使用 fscanf
进行输入的问题是,某些行会导致格式失败,文件不会在每次 while
循环迭代中前进,因此您会陷入困境.
可以通过使用fgets
抓取数据和sscanf
抓取数字来得到解决方案:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(void) {
int i = 0;
int ret = 0;
char buf[50];
FILE *file = fopen("score.txt", "r");
if (file == NULL) {
fprintf(stderr,"Unable to open file\n");
exit(1);
}
while (fgets(buf,sizeof(buf),file)) {
ret = sscanf(buf,"%d",&i);
if (ret == 1) { // we expect only one match
printf("%d\n", i);
} else if (errno != 0) {
perror("sscanf:");
break;
}
}
fclose(file)
return(0);
}
这将为您的输入输出:
20
2
我们检查 sscanf
的输出,因为它告诉我们格式是否正确匹配,这只会发生在带有整数的行上,而不是“NAME”行上。我们还检查“errno”,如果 sscanf 遇到错误,该“errno”将设置为非零。
我们使用 char buf[50];
声明一个具有 50 个槽的 char 数组,然后 fgets
使用该数组存储其读取的行;但是,如果该行长度超过 50 个字符,fgets
将会以 50 个字符 block 的形式读取该行,并且您可能无法获得所需的结果。
如果您希望将读取的整数存储到数组中,则必须声明一个数组,然后在每次读取时将该数组中的一个槽分配给您读取的 int 值,即 int_array[j ] = i
(其中 j
必须随您使用的每个插槽而变化)。我将把它作为练习来实现这一点。
关于c - 读取文件然后将数字存储在数组 C 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22240712/