【问题标题】:Why aren't my variables being saved? I've been testing this code and my variables aren't being saved into my struct array为什么我的变量没有被保存?我一直在测试这段代码,但我的变量没有保存到我的结构数组中
【发布时间】:2025-12-02 14:25:01
【问题描述】:

这是我的代码和变量的输出: 我还需要在我的 while 循环中添加什么,以便我的变量和方法可以工作。

int main() {
  FILE *ifp;
  ifp = fopen("processes.txt","r");
  if(ifp == NULL) {
      printf("Error Opening file.\n");
      exit(1);
  }

  char str[100];
  int i=0;

  while(fgets(str, 100, ifp) != NULL) {
    fscanf(ifp," %d %0.1f %d %d", &arr[i].pid, &arr[i].AT, &arr[i].duration, &arr[i].rank);
    i++;
  }
}
printf("ProceId AT   duration rank\n");

for (int j = 0; j < i - 1; ++j){
    printf("%d\t%0.1f\t%d\t%d\n",arr[j].pid,arr[j].AT,arr[j].duration,arr[j].rank );
}


ProceId AT   duration rank
1398    0.0     0       0
2306    0.0     0       0
3219    0.0     0       0
4478    0.0     0       0
5653    0.0     0       0
6399    0.0     0       0
7777    0.0     0       0

这是包含一行我不需要的字符串的文件,这就是我使用 fgets 的原因。

ProcessID   ArrTime Duration  Rank

1398        1.0     16      3
2306        4.5     6       7
3219        3.0     11      1
4478        2.0     3       5
5653        3.5     7       2
6399        4.0     8       6
7777        2.5     17      8   

【问题讨论】:

  • 好吧,我们看不到你是如何打印它们的,所以minimal reproducible example 会很有帮助。不清楚您为什么使用fgetsfscanf,您是否打算只从其他行读取?也许您只想在从fgets 获得的每一行上使用fscanfsscanf?您还应该始终检查 scanf 函数的返回值,以确保它们实际上解析了正确数量的项目。
  • while(fgets 是有问题的,(您尝试丢弃循环迭代中的一行),只丢弃文件的第一行然后不再调用 fgets 会更清晰。检查fscanf的返回值也很好,这样如果出现问题可以报告错误,而不是保存垃圾值

标签: c arrays struct


【解决方案1】:

改变这个:

fscanf(ifp," %d %0.1f %d %d", &arr[i].pid, &arr[i].AT, &arr[i].duration, &arr[i].rank);

到这里:

fscanf(ifp," %d %f %d %d", &arr[i].pid, &arr[i].AT, &arr[i].duration, &arr[i].rank);

因为您使用了无效的转换说明符。

下次注意编译器警告,它们通常会说明整个故事:

warning: invalid conversion specifier '.'
      [-Wformat-invalid-specifier]
        fscanf(ifp," %d %0.1f %d %d", &arr[i].pid, &arr[i].AT, &arr[i].d...
                       ~~~^
warning: format specifies type 'int *' but the argument has type
      'float *' [-Wformat]
        fscanf(ifp," %d %0.1f %d %d", &arr[i].pid, &arr[i].AT, &arr[i].d...
                              ~~                   ^~~~~~~~~~
                              %f
warning: data argument not used by format string
      [-Wformat-extra-args]
  ..." %d %0.1f %d %d", &arr[i].pid, &arr[i].AT, &arr[i].duration, &arr[i].ra...
     ~~~~~~~~~~~~~~~~~                                             ^

警告表明,由于转换说明符无效,%d 格式说明符用于结构的浮点字段(命名为 AT),然后一切都变得一团糟,因为您缺少一种格式说明符...

阅读更多How to only accept a certain precision (so many decimals places) in scanf?

【讨论】:

  • 哇,谢谢,我没有任何编译警告,我不敢相信这是我需要改变的一件事才能让它正常工作。再次感谢。
  • Clang 给了我警告,没有任何标志 @TheTrillestProgrammer。也许你正在使用 GCC。尝试使用-Wall 标志进行编译。很高兴我能帮上忙。
最近更新 更多