[英]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.