c语言从文件读取数据

用C语言把图片中的TXT里的数据读到一个数组里或者5个变量里

四个整型 一个浮点型, 所以 用数组的话 只能是用浮点型数组, 即float a[5];

或者用五个变量, 可以是四个整型,一个浮点型. int a,b,d,e; float c;

打开文件部分相同. 

FILE *fp = fopen("input1.txt", "r");

读取数据, 数组方式:

int i;
float a[5];
fscanf(fp, "%f,", &a[0]);
for(i = 1; i <5; i ++)
    fscanf(fp, "%f",&a[i]);

变量方式:

int a,b,d,e; 
float c;
fscanf(fp,"%d,%d%f%d%d", &a,&b,&c,&d,&e);
温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-11-13

代码:

#include<cstdio>

int main()
{
double datas[10];
FILE *f = fopen("input1.txt", "r");
for (int i = 0;i < 5;i++)
{
fscanf(f, "%lf", &datas[i]);
printf("%.1lf\n", datas[i]);
}
return 0;
}

测试结果:

追问

你用的什么编译器啊

第2个回答  2017-11-13
#include<stdio.h>
void main() { FILE *fp; int a,b,c,d; float e;
  if ( fp=fopen("input.txt","r") ) {
    fscanf(fp,"%d,%d",&a,&b);
    fscanf("%f%d%d",&e,&c,&d);
    fclose(fp);
    printf("%d %d %d %d %f\n",a,b,c,d,e);
  } else printf("无法打开文件'input.txt'。\n");
}

第3个回答  2017-11-13
float a[5];
FILE *fp;

fp=fopen("input1.txt","r");
for(int i=0;i<5;i++)
fscanf(f, "%f%*c", &a[i]);
fclose(fp);
相似回答