在 C 中使用 fscanf 扫描字符串

kim*_*ser 4 c string file scanf

请帮我解决一些问题。

该文件包含:

AAAA 111 BBB
CCC 2222 DDDD
EEEEE 33 FF
Run Code Online (Sandbox Code Playgroud)

代码是:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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]
Run Code Online (Sandbox Code Playgroud)

类型不对吗?有什么问题?

Nik*_* C. 9

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

fscanf(finput, "%s %i %s\n", a, &b, c);
Run Code Online (Sandbox Code Playgroud)

这相当于:

fscanf(finput, "%s %i %s\n", &a[0], &b, &c[0]);
Run Code Online (Sandbox Code Playgroud)

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

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

有关解释,请参阅:https : //stackoverflow.com/a/2528328/856199