2014-11-08 40 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