2013-10-02 25 views
0

我正在研究一個程序,該程序根據患者的身份證號碼和他們的血壓讀數讀取一組數據。然後程序將把所有的讀數加在一起,並得出一個平均值。它會顯示該平均值。這是我的計劃至今:未處理的內存異常

#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; 
} 

當我運行程序我得到這個錯誤:Microsoft C++異常:處0x756DB727血液Pressure.exe

未處理的異常的std :: invalid_argument內存位置0x0042F794。

我不太清楚這意味着什麼,但它打開了我以前從未見過的代碼列表。就像我說的,我不知道爲什麼它會拋出這個錯誤,或者錯誤的含義,但如果有人能幫助我,我會很感激。

回答

0

這條線:

cout << "Patient ID: " + id; 

是有缺陷的。您試圖將id附加到「患者ID:」,但這不是發生的情況。

字符串文字「Patient ID:」實際上是指向字符序列(即數組)的指針。當您使用加號時,您正在執行字符序列的內存地址和id之間的指針算術。如果id大於字符串的長度,這可能會導致您的程序嘗試訪問無效位置。

爲了解決這個問題,簡單地通過使兩個單獨的呼叫到<<操作打印ID後序:

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

感謝您的答覆後,不幸的是我做的,我現在得到一個錯誤,指出:未處理在Blood Pressure.exe的0x756DB727處出現異常:Microsoft C++異常:內存位置0x0052FB00處的std :: invalid_argument。 – emufossum13

+0

@ emufossum13在這種情況下,你仍然有另一個錯誤。對不起,但我不能發現它。 – ApproachingDarknessFish