我正在开发一个程序,根据患者的身份证号和血压读数读取一组数据。然后程序将所有读数加在一起并得出平均值。然后它会显示平均值。到目前为止,这是我的计划:
#include <iostream>
#include <string>
#include <conio.h>
#include <fstream>
using namespace std;
int main()
{
//Initialize Required Variables For Program
int patientCount;
string id;
string rHowMany; //String To Read From File
int howMany;
int howManyCount;
int avg = 0;
int avg2;
string line;
int number_lines = 0;
ifstream reader ("data.txt"); //Open The Data File To Be Read From
patientCount = 0;
while (getline(reader, line))
{
number_lines += 1;
}
//getline(reader, id); //Get the patients ID
//getline(reader, rHowMany); //Get How Many BP Records The Patient Has
for (number_lines; number_lines > 0; number_lines--)
{
reader >> id;
reader >> rHowMany;
howMany = stoi(rHowMany);
howManyCount = howMany;
patientCount += 1;
cout << "Patient ID: " + id;
for (howManyCount; howManyCount > 0; howManyCount--)
{
reader >> avg2;
avg = avg + avg2;
}
}
cout << avg;
cout << "\n";
cout << howMany;
avg = avg / howMany;
cout << "\n";
cout << avg;
_getch();
return 0;
}
当我运行程序时,我收到此错误:
Blood Pressure.exe中0x756DB727处的未处理异常:Microsoft C ++异常:内存位置0x0042F794处的std :: invalid_argument。
我不太清楚这意味着什么,但它打开了一个我从未见过的代码列表。就像我说的那样,我不确定为什么它会抛出这个错误,或者错误意味着什么,但如果有人可以帮助我,我会很感激。
答案 0 :(得分:0)
这一行:
cout << "Patient ID: " + id;
有缺陷。您正尝试将id
附加到“患者ID:”,但这不是正在发生的事情。
字符串文字“Patient ID:”实际上是指向一系列字符(即数组)的指针。使用加号时,您将在字符序列的内存地址和id之间执行指针运算。如果id大于字符串的长度,这可能会导致程序尝试访问无效位置。
要解决此问题,只需通过对<<
运算符进行两次单独调用,即可在序列后打印ID:
cout << "Patient ID: " << id; // no +