[英]Scanning strings with fscanf in C
Please, help me to fix some problems. 请帮我解决一些问题。
The file contains: 该文件包含:
AAAA 111 BBB
CCC 2222 DDDD
EEEEE 33 FF
The code is: 代码是:
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;
}
The code does work. 代码确实有效。 However, the following errors occur:
但是,会发生以下错误:
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]
Are the types wrong? 类型错了吗? What's the problem?
有什么问题?
Array names decay to a pointer to their first element, so in order to pass the addresses of the arrays to fscanf()
, you should simply pass the arrays directly: 数组名称衰减为指向其第一个元素的指针,因此为了将数组的地址传递给
fscanf()
,您应该直接传递数组:
fscanf(finput, "%s %i %s\n", a, &b, c);
This is equivalent to: 这相当于:
fscanf(finput, "%s %i %s\n", &a[0], &b, &c[0]);
But obviously using a
instead of &a[0]
is more convenient. 但显然使用
a
代替&a[0]
会更方便。
The way you wrote it, you're passing the same value (that's why it works), but that value has a different type : it's not a pointer to a char
anymore, but a pointer to an array of char
s. 你编写它的方式,你传递相同的值 (这就是它工作的原因),但是这个值有不同的类型 :它不再是指向
char
的指针,而是指向char
数组的指针。 That's not what fscanf()
is expecting, so the compiler warns about it. 这不是
fscanf()
所期望的,所以编译器警告它。
For an explanation, see: https://stackoverflow.com/a/2528328/856199 有关说明,请参阅: https : //stackoverflow.com/a/2528328/856199
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.