未处理的内存异常

Unhandled Memory Exception

本文关键字:异常 内存 未处理      更新时间:2023-10-16

我正在开发一个程序,该程序根据患者的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;
}

当我运行程序时,出现此错误:

在血压

.exe的 0x756DB727 处未处理的异常:Microsoft C++异常:内存位置 0x0042F794 处的 std::invalid_argument。

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

这一行:

cout << "Patient ID: " + id;

是有缺陷的。您正在尝试将id附加到"患者 ID:",但事实并非如此。

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

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

cout << "Patient ID: " << id; // no +