void readFile(void) {
FILE *file;
int i;
char line[100];
int testnr, testnr2, testnr3, testnr4;
//testnr = 1;
//testnr2 = 2;
//testnr3 = 3;
//testnr4 = 4;
file = fopen("test.txt","r");
fgets(line,500,file); // does not do anything with the first line
// read in 1,2,3,4
fscanf(file, "%i %i %i %i", &testnr, &testnr2, &testnr3, &testnr4);
printf("%i %i %i %i \n", testnr, testnr2, testnr3, testnr4);
fclose(file);
}
终端中的输出变为:1 32714 -275292160 32767
我该如何修复它,使其成为:1 2 3 4
?
最佳答案
您还需要读入整数之间的字符。
fscanf( file, "%i,%i,%i,%i", &nr, &nr2, &nr3, &nr4 );
另请注意,fscanf
返回成功读取的次数。所以你可以这样做:
int num_reads = fscanf( file, "%i,%i,%i,%i", ... );
if( num_reads != 4 )
{
// DO ERROR
}
else
{
// DO SUCCESS
}
关于c - 读取像 1,2,3,4 这样的行时如何在 c 中正确 fscanf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19965663/