Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C语言中从文件中读取和输出整数_C_File_Output_Scanf - Fatal编程技术网

在C语言中从文件中读取和输出整数

在C语言中从文件中读取和输出整数,c,file,output,scanf,C,File,Output,Scanf,我创建了一个包含以下内容的文件:“12 7-14 3-8 10” 我想输出整数类型的所有数字。但编译并运行程序后,我只得到第一个数字“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:

我创建了一个包含以下内容的文件:“12 7-14 3-8 10”

我想输出整数类型的所有数字。但编译并运行程序后,我只得到第一个数字“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);
}
#包括
main(){
文件*f;
int x;
f=fopen(“C:\\Users\\emachines\\Desktop\\ind\\in.txt”,“r”);
fscanf(f、%d、&x);
printf(“编号:%d”,x);
fclose(f);
}

我做错了什么?

使用
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
}
#包括
int main()//使用int main
{
文件*f;
int x;
f=fopen(“C:\\Users\\emachines\\Desktop\\ind\\in.txt”,“r”);
if(f==NULL)//如果文件打开失败
{
printf(“打开文件失败,正在退出…”);
返回-1;
}
printf(“数字为:”);
而(fscanf(f,%d,&x)==1)
printf(“%d”,x);
fclose(f);
return(0);//main返回int
}
谢谢!您使用了
while(fscanf(f,“%d”,&x)==1)
,所以我想问一下。
while(fscanf(f),%d,&x)==1)
是否等同于
while(!feof(f))
,或者不是?否。。