【问题标题】:Scanning strings with fscanf in C在 C 中使用 fscanf 扫描字符串
【发布时间】:2012-10-14 03:03:50
【问题描述】:

请帮我解决一些问题。

文件包含:

AAAA 111 BBB
CCC 2222 DDDD
EEEEE 33 FF

代码为:

int main() {
    FILE * finput;

    int i, b;
    char a[10];
    char c[10];

    finput = fopen("input.txt", "r");

    for (i = 0; i < 3; i++) {
        fscanf(finput, "%s %i %s\n", &a, &b, &c);
        printf("%s %i %s\n", a, b, c);
    }

    fclose(finput);
    return 0;
}

代码确实有效。但是,会出现以下错误:

format «%s» expects argument of type «char *», but argument 3 has type «char (*)[10]
format «%s» expects argument of type «char *», but argument 5 has type «char (*)[10]

类型错了吗?有什么问题?

【问题讨论】:

    标签: c string file scanf


    【解决方案1】:

    数组名称衰减为指向其第一个元素的指针,因此要将数组的地址传递给fscanf(),您应该直接传递数组:

    fscanf(finput, "%s %i %s\n", a, &b, c);
    

    这相当于:

    fscanf(finput, "%s %i %s\n", &a[0], &b, &c[0]);
    

    但显然使用a而不是&amp;a[0]更方便。

    按照您编写它的方式,您传递的是相同的 value(这就是它起作用的原因),但该值具有不同的 type:它不是指向不再是char,而是指向chars 数组的指针。这不是fscanf() 所期望的,因此编译器会发出警告。

    解释见:https://stackoverflow.com/a/2528328/856199

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-28
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 2017-10-12
      • 2016-05-04
      相关资源
      最近更新 更多