c - 从 c 中的 .txt 中提取数据

标签 c algorithm

我已阅读主题 How to extract data from a file in C但我仍然无法从 C 文件中提取数据,因为我有一个精确的请求。这是我必须处理的 .txt 示例:

2
3 
x x y z
x x y z
x x y z
4 5

前两个整数很重要。由于我们首先按此顺序有 2(=M) 和 3(=N),这意味着这些数字后面的方 block 的格式为 Nx(M+2),即 N 行数和 M+2列数和最后一行将有 M 个数字。

我假设 x、y 和 z 是 double 字,以突出显示我想要提取的内容。

我的目标是获得将生成的代码: M=2; N=3; x[N][M]={{x,x},{x,x},{x,x}}; y[N]={y,y,y}; z[N]={z,z,z}; t[M] = {4,5}; 对于文件中的任何输入。

这是我尝试过的方法,但它不起作用,因为我想我真的不知道如何管理我们读取文件的位置:

long i,j,M,N;
FILE *f;
f=fopen("file.txt","r");
fscanf(f,"%ld %ld",&M,&N);
double x[M][N],y[N],z[N],t[M];
for(i=0;i<N;i++)
{
    for(j=0;j<M;j++)
        fscanf(f,"%g",&x[i][j]);

    fscanf(f,"%g",&y[i]);
    fscanf(f,"%g",&z[i]);
}

for(j=0;j<M;j++)
    fscanf(f,"%g",&t[j]);

最佳答案

这是您问题的完整答案,此外还有一些保守的更改可以增强您的程序的稳定性。我使用的扫描码是%lg,兼容double数据类型。

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
   FILE *f;
   f = fopen("file.txt","r");
   if(!f)
   {
      perror("file open failed");
      exit(1);
   }

   long int i, j, M, N;    
   if(fscanf(f,"%ld %ld",&M,&N) != 2) {perror("error: invalid input."); exit(1);}
   double x[M][N], y[N], z[N], t[M];

   for(i = 0; i < N; i++)
   {
      for(j = 0; j < M; j++)
      {
          if(fscanf(f,"%lg",&x[i][j]) != 1) {perror("error: invalid input."); exit(1);}
      }
      if(fscanf(f,"%lg",&y[i]) != 1) {perror("error: invalid input."); exit(1);}
      if(fscanf(f,"%lg",&z[i]) != 1) {perror("error: invalid input."); exit(1);}
   }
   for(i = 0; i < M; i++)
   {
      if(fscanf(f,"%lg",&t[i]) != 1){perror("error: invalid input."); exit(1);}
   }

   if(fclose(f))
   {
      perror ("file close failed");
      exit(1);
   }
   return(0);
}

关于c - 从 c 中的 .txt 中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41516841/

相关文章:

c - 不存在的运算符的错误消息

c - 从 C 中的函数返回 C 字符串

javascript - 是否可以画一个包含婴儿床或棕褐色的完整圆圈?

algorithm - 给出大于或等于给定数字的最小总和的子集

python - 通过字典获取路径

javascript - 如何强制 node.js 进行更深层次的递归?

c++ - 隐藏复合数据类型的某些字段以防止写入(或读回)hdf5 文件

header 可以在没有文件的情况下存在吗?

algorithm - 我需要一种算法来遍历带有可选节点和替代节点的树,以计算所有可能的路径

c - 平方根 union 和位移位