具有扫描串问题从文件 [英] Having problems with scanning strings from a file
问题描述
请,帮我解决了一些问题。
Please, help me to fix some problems.
该文件包含:
AAAA 111 BBB
CCC 2222 DDDD
EEEEE 33 FF
的code是:
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;
}
的code不工作。但是,会出现以下错误:
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?
推荐答案
数组名衰减到一个指向自己的第一个元素,所以为了数组的地址传递给的fscanf()
,您应该简单地直接传递数组:
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(finput, "%s %i %s\n", a, &b, c);
这是等同于:
fscanf(finput, "%s %i %s\n", &a[0], &b, &c[0]);
但很明显,使用 A
,而不是&放大器;一个[0]
更方便
你写它的方式,你传递相同的值的(这就是为什么它的作品),但该值都有不同的键入的:它不是一个指针一个字符
了,但指针的字符
秒的数组。这不是什么的fscanf()
期待,所以编译器警告一下。
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. That's not what fscanf()
is expecting, so the compiler warns about it.
有关说明,请参阅: http://stackoverflow.com/a/2528328/856199
这篇关于具有扫描串问题从文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!