0

我正在开发一个程序,该程序根据患者的 ID 号和他们的血压读数读取一组数据。然后程序会将所有读数加在一起并得出平均值。然后它将显示该平均值。到目前为止,这是我的程序:

#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。

我不太确定这意味着什么,但它会打开一个我以前从未见过的代码列表。就像我说的那样,我不确定它为什么会抛出这个错误,或者这个错误意味着什么,但如果有人可以帮助我,我将不胜感激。

4

1 回答 1

0

这一行:

cout << "Patient ID: " + id;

有缺陷。您正在尝试附加id到“Patient ID:”,但这不是正在发生的事情。

字符串文字“Patient ID:”实际上是一个指向字符序列(即数组)的指针。当您使用加号时,您正在执行字符序列的内存地址和 id 之间的指针运算。如果 id 大于字符串的长度,这可能会导致您的程序尝试访问无效的位置。

要解决这个问题,只需在序列之后通过对运算符进行两次单独调用来打印 id <<

cout << "Patient ID: " << id; // no +
于 2013-10-02T00:30:30.147 回答