如果输入不符合指定格式,C 中的 sscanf 会做什么?

问题描述 投票:0回答:1
#include <stdio.h>
int main(int argc, const char* argv[]){
    FILE *fp = fopen("input.txt", "r");
    char buffer[256];
    int n, a, b;
    n = a = b = 0;
    while(fgets(buffer,250,fp)){
        n = sscanf(buffer, "%d %d", &a, &b);
        printf("%d %d %d\n", a, b, n);
    }
    fclose(fp);
    printf("Next Part\n");
    fp = fopen("input.txt", "r");
    n = a = b = 0;
    while(0 < (n = fscanf(fp,"%d %d", &a, &b))){
        printf("%d %d %d\n", a, b, n);
    }

    return 0;
}

input.txt 包含以下行:

1 2 3
4 abc 5 6
7 8
the 1 next 2 line 3 is blank

4 5 the above line is blank 6
7 8

我知道第一行打印将是“1 2 2”,因为 n 被设置为 sscanf 的返回值(它返回 2,因为我假设两个整数都被读取)。然而,我不确定第二行会产生什么?如果我能让人帮我解决并解释第二行,我将不胜感激。我也很困惑当循环遇到空行时会发生什么?

c while-loop scanf fgets
1个回答
0
投票

无可否认,

sscanf
文档读起来很乏味。

这个小例子展示了如果输入与格式字符串不匹配会发生什么。

#include <stdio.h>

int main(void)
{
  int a, b;
  char input1[] = "1 2 3 4 whatever";
  int n = sscanf(input1, "%d %d", &a, &b);
  printf("sscanf has read %d items. a = %d, b = %d\n", n, a, b);

  char input2[] = "11 foo bar";
  n = sscanf(input2, "%d %d", &a, &b);
  printf("sscanf has read %d items. a = %d, b = %d\n", n, a, b);
}

输出为:

sscanf has read 2 items. a = 1, b = 2
sscanf has read 1 items. a = 11, b = 2

在第一个

sscanf
期间,有 2 个项目被读取为
1
2
%d %d
格式字符串匹配。

在第二个

sscanf
期间,仅读取了 1 个项目,因为只有
11
与第一个
%d
匹配,但
foo
与第二个
%d
不匹配。
b
未修改。

© www.soinside.com 2019 - 2024. All rights reserved.