2014-11-08 57 views
0

我創建了內容的文件:'12 7 -14 3 -8 10'讀取並輸出從文件整數用C

我要輸出類型整數的所有數字。但是在編譯和運行該程序後,我只得到了第一個數字「12」

這裏是我的代碼:

#include <stdio.h> 

main(){ 
    FILE *f; 
    int x; 
    f=fopen("C:\\Users\\emachines\\Desktop\\ind\\in.txt", "r"); 
    fscanf(f, "%d", &x); 
    printf("Numbers: %d", x); 
    fclose(f); 
} 

我在做什麼錯?

回答

1

您掃描一個整數從文件使用fscanf並打印它。您需要一個循環來獲取所有整數。 fscanf返回成功匹配和分配的輸入項目數。在您的情況下,fscanf在成功掃描時返回1。所以只需從文件中讀取整數,直到fscanf返回0像這樣:

#include <stdio.h> 

int main() // Use int main 
{ 
    FILE *f; 
    int x; 

    f=fopen("C:\\Users\\emachines\\Desktop\\ind\\in.txt", "r"); 

    if(f==NULL) //If file failed to open 
    { 
     printf("Opening the file failed.Exiting..."); 
     return -1; 
    } 

    printf("Numbers are:"); 
    while(fscanf(f, "%d", &x)==1) 
    printf("%d ", x); 

    fclose(f); 
    return(0); //main returns int 
} 
+0

謝謝!你用'while(fscanf(f,「%d」,&x)== 1)',所以我想問。 'while(fscanf(f,「%d」,&x)== 1)'等於'while(!feof(f))',否? – 2014-11-08 14:01:17

+0

不能。['while(!feof(f))'wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong)。 – 2014-11-08 14:43:13