使用C中的fscanf跳过行的剩余部分

我正在阅读一个文件,在读完一个数字之后,我想跳过剩下的那一行。 这是一个文件的例子

2 This part should be skipped 10 and also this should be skipped other part of the file 

目前我通过使用这个循环来解决这个问题:

 char c = '\0'; while(c!='\n') fscanf(f, "%c", &c); 

然而,我想知道是否没有更好的方法来做到这一点。 我试过这个,但由于某种原因,它不起作用:

 fscanf(f, "%*[^\n]%*c"); 

我本以为这会读到新行的所有内容然后再读新行。 我不需要内容,所以我使用*运算符。 但是,当我使用此命令时没有任何反应。 光标未移动。

我建议你使用fgets()然后使用sscanf()来读取数字。 scanf()函数容易出错,你可以很容易地得到格式字符串错误,这似乎适用于大多数情况,并且当你发现它不能处理某些特定的输入格式时会出现意外故障。

快速搜索SO上的scanf()问题将显示人们在使用scanf()时出错的频率并遇到问题。

相反,fgets()+ sscanf()给出了更好的控制,你知道你已经读了一行,你可以处理你读取的行读取整数:

 char line[1024]; while(fgets(line, sizeof line, fp) ) { if( sscanf(line, "%d", &num) == 1 ) { /* number found at the beginning */ } else { /* Any message you want to show if number not found and move on the next line */ } } 

您可能希望根据文件line的格式更改从line读取num的方式。 但在你的情况下,似乎整数位于第一位或根本不存在。 所以上面的工作正常。

 #include  int main(){ FILE *f = fopen("data.txt", "r"); int n, stat; do{ if(1==(stat=fscanf(f, "%d", &n))){ printf("n=%d\n", n); } }while(EOF!=fscanf(f, "%*[^\n]")); fclose(f); return 0; }