fscanf - 我不知道我在这里做错了什么

Sar*_*ara 5 c scanf

 char id;
 int num, r;
 if (argc != 2) {
   printf("error\n");
   exit(1);
 }

 FILE *file = fopen(argv[1], "r");
 if (file == NULL) {
   printf("error\n");
   exit(1);
  }

  while ((r = fscanf(file, "%c\t%d", &id, &num)) != EOF) {
    if(r == 2) {
      printf("id: %c, value: %d\n", id, num);
    }
    else if (r!=2) {
      printf("bad input\n");
    }
  } 
Run Code Online (Sandbox Code Playgroud)

我正在尝试阅读的文件如下:

我10

我12

d 10

d 12

(字符/整数是制表符分隔的).我的输出是:

id:i,价值:10

输入不好

id:i,价值:12

输入不好

id:d,值:10

输入不好

id:d,值:12

输入不好

我究竟做错了什么?如果文件格式不正确,则只应打印"输入错误".上面的文件演示了格式正确的文件.我不明白如何r == 2和r != 2同时(两种情况都以某种方式得到满足).

ash*_*n33 4

使用

while((r = fscanf(file, " %c\t%d", &id, &num)) != EOF)  //Whitespace before %c 
Run Code Online (Sandbox Code Playgroud)

可能会解决你的问题。因为当你使用

fscanf(file, "%c\t%d", &id, &num)
Run Code Online (Sandbox Code Playgroud)

然后它留下一个换行符,该换行符将在下一次迭代中使用。当你的下一次迭代时,你会id得到\n并num得到角色。

但是,当您在前面放置额外的空格时,%c会告诉fscanf()您忽略空格(包括制表符、空格或换行符)。因此你fscanf()得到两个参数(字符和数字)。

  • 看来成功了!您能解释一下为什么空格会产生差异吗?太感谢了! (3认同)