我有一个文件,其中包含这样的整数:
11_12_34_1987_111_
其中 _
代表空格,我想将它们存储在最大大小为 100 的整数数组中。我试过这个
i=0;
while((c=fgetc(f))!=EOF)
{
fscanf( f, "%d", &array[i] );
i++;
}
但是打印这个数组在我的屏幕上给我无限的值。
最佳答案
fgetc
从流 f
中读取下一个字符并将其作为转换为 int
的 unsigned char
返回>。因此,您正在存储从流中读取的字符的 (ascii) 代码。
您应该使用 fscanf
或 fgets
和 sscanf
的组合从流中读取整数,将它们读取为整数。您可以检查 fscanf
的返回值是否为 1
并继续从文件中读取。这是我的建议。
FILE *fp = fopen("input.txt", "r");
int array[100];
int i = 0, retval;
if(fp == NULL) {
printf("error in opening file\n");
// handle it
}
// note the null statement in the body of the loop
while(i < 100 && (retval = fscanf(fp, "%d", &array[i++])) == 1) ;
if(i == 100) {
// array full
}
if(retval == 0) {
// read value not an integer. matching failure
}
if(retval == EOF) {
// end of file reached or a read error occurred
if(ferror(fp)) {
// read error occurred in the stream fp
// clear it
clearerr(fp);
}
}
// after being done with fp
fclose(fp);
关于c - 从以空格分隔的文件中读取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22985871/