【问题标题】:getting fscanf to store in structs in C让 fscanf 存储在 C 中的结构中
【发布时间】:2014-06-10 09:25:57
【问题描述】:

我有一个任务,我需要从文件中获取 RLC 电路的值并计算谐振频率,但是我的问题是当我使用 fscanf 函数时,它只读取文件的第一行,其余的输出为零.

#include <stdio.h>
data

 int h;
typedef struct cct
{
  int code[50];
  float R[50];
  float L[50];
  float C[50];
} CCT;

 int read(CCT cct[], int n_p, FILE* fp){
   char temp;

   if(fp==NULL){
       printf("Error\n");
       return -1;
   }
   fscanf(fp,"%d,%f,%e,%e\n", cct[n_p].code, cct[n_p].R,cct[n_p].L, &cct[n_p].C);

}
int main()
{
   FILE* fp = fopen("U://datafile.txt", "rt");
   int i = 0;
   CCT cct[50];
   int size;

   while (!feof(fp)) {
       read(cct, i, fp);
       i++;
   }
   size = i;

   for (i = 0; i < size; ++i)
     printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code[i], cct[i].R[i],
            cct[i].L[i], cct[i].C[i]);

 scanf("%d",&h);
   fclose(fp);
}

这是数据文件

    1,4.36,2.23e-2,4.65e-8
    2,4.57,2.01e-2,5.00e-8
    3,3.99,2.46e-2,4.82e-8
    4,4.09,2.60e-2,4.70e-8

如果有人能指出为什么它只得到第一行,我将不胜感激。谢谢

【问题讨论】:

  • 我会在字符串缓冲区中使用fgets(),然后在字符串上使用 sscanf() 而不是fscanf() 它往往会更可靠地工作。
  • 约翰你介意向我解释一下,因为我是编程新手,谢谢。
  • 你想要CCT cct[50]; 吗?或CCT cct;
  • 不清楚您要做什么。 fscanf 将只读取 struct cct 的每个数组字段的第一个元素。如果您在 50 个 ccts 中的每个 codeRLC 中都有 50 个,那么您有某种矩形值表,并且您正在阅读的只是第一列。然后你打印cct[i].code[i] 这是 diagonal 元素。这不可能是对的。
  • @n.m.我试图单独获取每组值,以便我可以使用它们进行计算,所以最后我得到了一种代码和频率表。

标签: c struct scanf


【解决方案1】:
fscanf(fp,"%d,%f,%e,%e", cct[n_p].code, cct[n_p].R,cct[n_p].L, cct[n_p].C);
...
printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code[0], cct[i].R[0], cct[i].L[0], cct[i].C[0]);

可能类似于以下内容

#include <stdio.h>

typedef struct cct {
  int code;
  float R;
  float L;
  float C;
} CCT;

int h;

int read(CCT cct[], int n_p, FILE* fp){
   char temp;

   if(fp==NULL){
       printf("Error\n");
       return -1;
   }
   fscanf(fp,"%d,%f,%e,%e\n", &cct[n_p].code, &cct[n_p].R, &cct[n_p].L, &cct[n_p].C);
}
int main(){
   FILE* fp = fopen("U://datafile.txt", "rt");
   int i = 0;
   CCT cct[50];
   int size;

   while (!feof(fp)) {
       read(cct, i, fp);
       i++;
   }
   size = i;

   for (i = 0; i < size; ++i)
     printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code, cct[i].R, cct[i].L, cct[i].C);
scanf("%d",&h);
   fclose(fp);
}

【讨论】:

  • 谢谢它成功了,请你解释一下为什么?再次感谢
  • @user3570628 , fscanf(fp,"%d,%f,%e,%e", cct[n_p].code, cct[n_p].R... 表示fscanf(fp,"%d,%f,%e,%e", &amp;cct[n_p].code[0], &amp;cct[n_p].R[0]...
【解决方案2】:

CCT 由多个数组组成(您有数组的数组,这对练习来说是错误的,但这不是重点),并且您总是写入数组的零元素。例如 fscanf() 中的 cct[n_p].code 是数组的地址,与 cct[n_p].code[0] 的地址相同。然后在输出循环中打印 code[i],除了 i == 0 之外它是空白的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多