【问题标题】:Read ANOTHER new line using fscanf in C在 C 中使用 fscanf 读取另一个新行
【发布时间】:2013-06-25 01:51:42
【问题描述】:

假设我有一个文件要读取:

//it may contain more than 2 lines
12 6
abadafwg

假设现在我已经像这样阅读了第一行:

char input[999];
while(!feof(fpin))
{
    fscanf(fpin, " %[^\n]", input);
    //do something here with these numbers
    //should do something here to read 2nd line
}

这是我的问题,我如何读取该文件的第二行? 请帮忙QAQ

【问题讨论】:

  • 'fscanf(fpin, " %[^\n]", input)' 相同但有空格
  • @PHIfound 这是一个字符串
  • 你试过运行这个吗?

标签: c file-io scanf


【解决方案1】:

建议不要使用fscanf(fpin, "%[^\n]", input),而是使用fgets(),因为这样可以防止缓冲区溢出。您可以将其用于两行,然后根据需要进行解析。

if (fgets(input, sizeof(input), fpin) == 0) {
  // handle error, EOF
}
int i[2];
int result = sscanf(input,"%d %d", &i[0], &i[1]);
switch (result) {
  case -1: // eof
  case 0: // missing data
  case 1: // missing data
  case 2: // expected
}
if (fgets(input, sizeof(input), fpin) == 0) {
  // handle error, EOF
}
// use the 'abadfwg just read

【讨论】:

  • 好的...但实际上,该文件超过 2 行,我不应该知道它包含多少行。我只知道第一行是2个数字,第二行是一个字符串,第三行是2个数字,等等。我需要用这2个数字做一些事情然后使用字符串,所以.....btw,老师推荐我们使用 fscanf...
  • 将 2 次读取放入一个循环中以应对 N 对行,观察结果 == EOF (-1) 表示读取文件完成。如果你想使用fscanf(),试试result = fscanf(fpin, "%d %d", &i[0], &i[1]); 和``result = fscanf(fpin, " %[^\n]", input);. Note the leading spaces consumes whitespace, including any previous un-read \n`。
【解决方案2】:

您提供的代码将读取程序中的所有行(while 循环的每次迭代一行),而不仅仅是第一行。 【我刚刚测试过了】

【讨论】:

    猜你喜欢
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    相关资源
    最近更新 更多