c - 我在将文件中的输入读取到数组结构中时遇到问题

标签 c codeblocks

这是我遇到的问题。基本上结构定义正确,但是编译器在尝试从给定文件读取输入时抛出错误。我可以在案例之前的 while 循环中浏览菜单,然后执行选项“a”或“A”并获取患者编号。然后我可以打开该文件,但无法将文件中的任何信息读取到结构变量中。它只是终止代码。我尝试读取的文件格式如下: 时间 BP_舒张压 BP_收缩压 01 80 120 02 81 124 03 78 118 等等

时间温度 01 98.7 02 99.0 03 98.5 等等

时间率 01 68 02 70 03 65 等等

我应该从文件中读取信息,将它们放入变量中,然后根据以下方程确定给定日期的健康得分: 𝑓(𝑡𝑖𝑚𝑒,𝑡𝑒𝑚𝑝,𝑝𝑟𝑒𝑠𝑠,𝑟𝑎𝑡𝑒) = 15*𝑡𝑒𝑚𝑝+35*𝑝𝑟𝑒𝑠 𝑠+25*𝑟𝑎𝑡𝑒 +25

其中:  temp 基于时间 t 时的体温,定义为: 𝑡𝑒𝑚𝑝 = {1 𝑖𝑓 97𝐹 ≤ 𝐵𝑇 ≤ 99 0 𝑜𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒
 压力基于时间 t 时的血压,定义为: 𝑝𝑟𝑒𝑠𝑠 = { 1 𝑖𝑓 𝐵𝑃𝐷 ≤ 80 𝑎𝑛𝑑 𝐵𝑃𝑆 ≤ 120 0.5 𝑖𝑓 80 < 𝐵𝑃𝐷 ≤ 89 𝑜𝑟 120 < 𝐵𝑃 𝑆 ≤ 139 0 𝑖𝑓 𝐵𝑃𝐷 ≥ 90 𝑜𝑟 𝐵𝑃𝑆 ≥ 140
心率基于时间 t 结束时的心率,基于一些 Δt,通常为 15 至 60 秒,定义为: 𝑟𝑎𝑡𝑒 = {1 𝑖𝑓 60 ≤ 𝐻𝑅 ≤ 100 0 𝑜𝑡ℎ𝑒𝑟𝑤𝑖𝑠 𝑒

我还没有到达该部分,因为我不知道如何将信息放入变量中。因此我无法对上述数据进行任何计算。

如果选择选项 d),程序应询问用户计算健康分数的时间点。输入有效时间(即应在给定的时间间隔内)后,程序应显示: A。包含 BT、BP 和 HR 值的表, b.检测任何状况的报告(即正常/高血压前期/ 高血压)如上所述,以及 C。使用等式获得的 HealthScore 值1.

如果选择选项 e),则应显示每个变量的统计参数(在时间间隔内)的表格。这包括最小值、最大值、平均值和标准偏差。

还应该进行测试,以确保程序的所有条目都在适当的范围内。

我希望这是对我遇到的问题的更好解释。另外,此时作业已经迟到了,但我仍然想了解我做错了什么。任何帮助将非常感激。

    #include<stdio.h>
    #include<stdlib.h>


    struct bloodPressure{
       int time;
       double pressD;
       double pressS;
    };

    struct temp{
       int time;
       double temp;
    };

    struct rate{
       int time;
       double r;
    };

    struct bloodPressure BP[55];
    struct temp T[55];
    struct rate R[55];
    int main()
      {
            int timeStart,
                timeEnd,
                timeSelect;
          double minTemp,
                 maxTemp,
                 avgTemp,
                 stdTemp,
                 minPressD,
                 maxPressD,
                 avgPressD,
                 stdPressD,
                 minpressS,
                 maxPressS,
                 avgPressS,
                 stdPressS,
                 minRate,
                 maxRate,
                 avgRate,
                 stdRate,
                 score;
          char fileName[140],
               fileNameBuffer[150],
               patientNum[5],
               menuSelect = "a";
          FILE *fp;



          while (menuSelect)
          {
             printf("Please select from the following list:\n");
             printf("a/A: Enter patient number\n");
             printf("b/B: Enter file folder location\n");
             printf("c/C: Enter time interval\n");
             printf("d/D: Get health score\n");
             printf("e/E: Get statistical data\n");
             printf("f/F: Exit the program\n");
             scanf("%c", &menuSelect);

             switch(menuSelect)
             {
                // code to enter patient ID number
                case 'a':
                case 'A':
                {
                   // ask user for the patient's ID number
                   printf("Please enter the Patient's ID number:\n");
                   scanf("%s", &patientNum);

                   printf("%s", patientNum);

                   // break out of switch statement and return to main                 
                   // menu
                   break;
                }

                // code to enter file location
                case 'b':
                case 'B':
                {
                   printf("Please enter the file location:\n");
                   scanf("%s", &fileName);

                   // if file for blood pressure does not open, display 
                   // error and return to main menu
                   sprintf(fileNameBuffer, "%sBP_%s.txt", fileName, 
                   patientNum);
                   fp = fopen(fileNameBuffer, "r");
                   printf("%s \n", fileNameBuffer);
                   if (fp == NULL)
                   {
                      printf("cannot open file");
                   }

                   // if file opens, read information from the file
                   // else
                   {
                      printf("file is being read\n");
                      // read in variables from blood pressure file into 
                      // blood pressure structure
                      while (!feof (fp))//int i = 0; i < 55; i++)
                      {
                         int i = 0;
                         fscanf(fp, '%d %lf %lf', BP[i].time, 
                         BP[i].pressD, BP[i].pressS);
                         printf("%d", BP[i].time);
                         if (++i >= 55)
                         {
                            break;
                         }
                      }

                      // close the blood pressure file
                      fclose(fp);
                   }

                   // if file for blood temperature does not open, display 
                   // error and return to main menu
                   if (fp = fopen(("%sBT_%d.txt", fileName, patientNum), 
                   'r') == NULL)
                   {
                      printf("cannot open file");
                   }

                   // if file opens, read information from the file
                   else
                   {
                      // read in variables from heart rate file into blood 
                      // pressure structure
                      while (!feof (fp))
                      {
                         int i = 0;
                         fscanf(fp, '%d %lf', &(T[i].time), &(T[i].temp));
                         if (++i >= 55)
                         {
                            break;
                         }
                      }

                      // close the heart rate file
                      fclose(fp);
                   }

                   // if file for heart rate does not open, display error 
                   // and return to main menu
                   if (fp = fopen(("%sHR_%d.txt", fileName, patientNum), 
                   'r') == NULL)
                   {
                      printf("cannot open file");
                   }

                   // if file opens, read information from the file
                   else
                   {
                      // read in variables from heart rate file into blood         
                      // pressure structure
                      while (!feof (fp))
                      {
                         int i = 0;
                         fscanf(fp, '%d %f', &(R[i].time), &(R[i].r));
                         if (++i >= 55)
                         {
                            break;
                         }
                      }

                      // close the blood pressure file
                      fclose(fp);
                   }

                   // break out of switch statement and return to main 
                   // menu
                   break;
                }

                // code to enter time interval
                case 'c':
                case 'C':
                {
                   // ask user for start and end times for the time 
                   // interval
                   printf("Please enter the starting time:\n");
                   scanf('%d', timeStart);
                   printf("Please enter the ending time:\n");
                   scanf('%d', timeEnd);

                   // break out of switch statement and return to main 
                   // menu
                   break;
                }

                // code to calculate health score
                case 'd':
                case 'D':
                {

                   break;
                }

                // code to calculate statistical data
                case 'e':
                case 'E':
                {

                   break;
                }

                // code to exit the program
                case 'f':
                case 'F':
                {
                   printf("You have chosen to exit the program\n");
                   exit(1);
                }

                default:
                {
                   printf("Error: Please enter a valid menu option (a-f or 
                   A-F)");
                   break;
                }
             }
          }



        return 0;
      }

最佳答案

问题更改后进行编辑 - 见下文

<小时/>

您的代码中的很多内容不会被编译器接受 - 以下是您可以进行的一些改进:

  1. C 中的字符串需要双引号,因此用 " 而不是 '
  2. 变量应在使用前声明。例如,在您的代码中,未声明 fpfileName,并且 BP 被声明为类型别名(使用 typedef )而不是变量。
  3. 存在一些小错误,例如注释了 else 语句,以及没有用大括号 } 结束该条件的 if 部分。
  4. fopen() 不接受您提供的文件名的构造 - 您必须首先在对 sprintf() 的单独函数调用中执行此操作。
  5. 我的编译器对 if (fp = fopen(...) == NULL) 的构造不太感兴趣,尽管其他编译器可能会接受它。该语句可以拆分。
  6. fscanf()语句中,有三件事:
    • 索引[i]位于错误的位置,
    • i 未定义,也没有增加到下一个值,并且没有检查它是否达到最大值
    • 小要点:要读取 double 类型的值,您可以使用扫描字符串 %lf(长 float )。

刚开始时,C 是一门相当难的语言,所以不用担心...这是我对它的理解(在我的计算机上运行正常):

#include <stdio.h>

// structure definitions
struct bloodPressure{
    int time[55];
    double pressD[55];
    double pressS[55];
};

// declarations
struct bloodPressure BP;
char fileName[100], fullname[110];
int i = 0;
const int patientNum = 1;
FILE *fp;

// start of problem
int main() {
    printf("Please enter the file location:\n");
    scanf("%s", fileName);
    sprintf(fullname, "%sBP_%d.txt", fileName, patientNum);

    // if file for blood pressure does not open, display error and 
    // return to main menu
    fp = fopen(fullname, "r");
    if (fp == NULL)
    {
        printf("cannot open file");
    }

    // if file opens, read information from the file
    else
    {
        // read in variables from blood pressure file into blood 
        // pressure structure
        while (!feof (fp))    //int i = 0; i < 55; i++
        {
            fscanf(fp, "%d %lf %lf", &(BP.time[i]), &(BP.pressD[i]), &(BP.pressS[i]));
            if (++i >= 55) break;
        }
        // close the blood pressure file
        fclose(fp);
    }
}

您可能会考虑更改struct BloodPressure的定义,以便它保存一个测量的压力数据,然后创建一个此类结构的数组,例如

struct bloodPressure BP[55];

而不是这里的结构,而是保存数组的结构。对我来说这似乎更符合逻辑。

<小时/>

编辑

由于您重写了问题和程序(我认为改进了很多),所以我正在编辑答案。

I can open the file but I cannot read any information from the file into the structure variables. it just terminates the code.

在第 109 行,您的 fscan 扫描模式仍然是单引号的(引号应该是 ")。其他一些地方也是如此,例如第 188 行。

顺便说一句,第 101 行中的 else 语句仍然被注释掉。

一般来说,你的编码进步很快。如果您告诉编译器在您执行可能导致错误的操作时发出警告,这可能会有所帮助。许多编译器接受选项-Wall(Warn at all things it does not like)。

关于c - 我在将文件中的输入读取到数组结构中时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53572817/

相关文章:

c - 用 C 语言打印位集

c++ - 编译 Box2D 时创建 libBox2D.a?

c++ - 来自文本字段Win32 API的整数值

java - 将可执行文件链接到代码块

c - If else 参数被忽略

c - C 程序中的 stdout 转义查询和 stdin 冲突(无 ncurses)

c - 重新分配() : invalid next size: 0x0000000002119010

c++ - 在 xcode 4 中, "other c flags"和 "other c++ flags"有什么区别?

c - 在 C 中使用 printf 或 printstring 格式化文本

c++ - jpeg-8d 库的链接(或正确安装和链接)