1
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

4

1 回答 1

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
}
于 2013-11-13T22:27:29.653 回答