簡體   English   中英

使用fscanf循環無法達到EOF

[英]Can't reach EOF with fscanf loop

Helo,當我繼續我的HW項目時,我被困在閱讀EOF的過程中,由於這個循環,它被永遠困住了,很顯然,輸入永遠不會獲得EOF的價值,我在做什么錯?

int main ()
{
FILE *ffil;
char input;
ffil=fopen("a.csv","r");
printf("error0");
do
{
    fscanf("%c",&input);
}while(input!=EOF);
fclose(ffil);
return 0;
}

scanf不能那樣工作。 另外, EOF不適合char 如果要逐個字符閱讀直到EOF ,請按慣用的方式進行:

int input;  /* int, not char! */

while ( (input = getchar()) != EOF )
{
    /* do stuff with 'input' here. */
}

如果您真的想使用scanf ,可以。 它返回成功轉換的值的數量,因此您可以使用它代替測試EOF

char input;  /* char, not int! */

while ( scanf("%c", &input) == 1 )  /* loop while scanf succeeds */
{
    /* do stuff with 'input' here */
}

這兩個都是從stdin讀取的,但是看來您的測試確實想從ffil讀取。 如果是這種情況(您的問題尚不清楚),請按如下所示修改以上示例:

int input;  /* int, not char! */

while ( (input = fgetc(ffil)) != EOF )
{
    /* do stuff with 'input' here. */
}

要么

char input;  /* char, not int! */

while ( fscanf(ffil, "%c", &input) == 1 )  /* loop while scanf succeeds */
{
    /* do stuff with 'input' here */
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM