在 C 中用 fscanf 跳过剩余的行 [英] Skip remainder of line with fscanf in C

查看:54
本文介绍了在 C 中用 fscanf 跳过剩余的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一个文件,在阅读了一个数字后,我想跳到该行的剩余部分.一个文件的例子是这个

I'm reading in a file and after reading in a number, I want to skip to remaining part of that line. An example of a file is this

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

目前我使用这个循环解决了这个问题:

At the moment I solve this by using this loop:

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

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

I was however wondering whether there isn't a better way of doing this. I tried this, but for some reason it isn't working:

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

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

I would have expected this to read everything up to the new line and then also read the new line. I don't need the content, so I use the * operator. However, when I use this command nothing happens. The cursor isn't moved.

推荐答案

我建议你使用 fgets() 然后 sscanf() 读取数字.scanf() 函数容易出错,您很容易弄错格式字符串,这在大多数情况下似乎都有效,但在某些情况下,当您发现它无法处理某些特定输入格式时,会意外失败.

I suggest you to use fgets() and then sscanf() to read the number. scanf() function is prone to errors and you can quite easily get the format string wrong which may seem to work for most cases and fail unexpectedly for some cases when you find it doesn't handle some specific input formats.

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

A quick search for scanf() problems on SO would show how often people get it wrong and run into problems when using scanf().

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

Instead fgets() + sscanf() gives would give you better control and you know for sure you have read one line and you can process the line you read to read integer out it:

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 读取 num 的方式.但是在您的情况下,该整数似乎首先位于或根本不存在.所以上面的方法可以正常工作.

You may want to change how you read num from line depending on the format of lines in the file. But in your case, it seems the integer is either located at first or not present at all. So the above will work fine.

这篇关于在 C 中用 fscanf 跳过剩余的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆