[英]Scanning strings with fscanf in C
请帮我解决一些问题。
该文件包含:
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]
类型错了吗? 有什么问题?
数组名称衰减为指向其第一个元素的指针,因此为了将数组的地址传递给fscanf()
,您应该直接传递数组:
fscanf(finput, "%s %i %s\n", a, &b, c);
这相当于:
fscanf(finput, "%s %i %s\n", &a[0], &b, &c[0]);
但显然使用a
代替&a[0]
会更方便。
你编写它的方式,你传递相同的值 (这就是它工作的原因),但是这个值有不同的类型 :它不再是指向char
的指针,而是指向char
数组的指针。 这不是fscanf()
所期望的,所以编译器警告它。
有关说明,请参阅: https : //stackoverflow.com/a/2528328/856199
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.