为什么fscanf在读取字符时失败

Why is fscanf failing while reading characters?

本文关键字:失败 字符 读取 fscanf 为什么      更新时间:2023-10-16

我有以下标题为"data.txt"的示例数据文件:

a<tab>b<tab>c<newline>
a<tab>b<tab>c<newline>

和以下代码:

#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main()
{
  char a,b,c;
  FILE* fin = fopen("data.txt","r");
  fscanf(fin,"%c %c %c",&a,&b,&c);
  cout<<a<<" "<<b<<" "<<c<<endl;
  fscanf(fin,"%c %c %c",&a,&b,&c);
  cout<<a<<" "<<b<<" "<<c<<endl;
  fclose(fin);
  return 0;
}

编译并运行时,其输出如下:

a b c
     a b

我期望看到:

a b c
a b c

怎么了?

您没有跳过读取的第三个和第四个字符之间的空白-您需要在其中一个格式字符串中使用另一个空格。

(为什么在C++中使用fscanf?)