2011-03-28 112 views
0

我要解決以下任務:MVS C++錯誤:串標超出範圍

有被賦予一個文本文件「pesel.txt」,其中包含150所國家認同。每行包含一個國家標識,這是一個11位數字編號。前兩位數字從左邊開始確定年份,一個人出生在哪一年,後兩位數字決定月份,下兩個決定日期。

爲了縮短:0-1 =年

數字 位2-3 =月 數字4-5 =天 位6-11 =確定別的東西,是什麼並不重要

我需要閱讀這個文件,檢查有多少人在十二月出生。我想這以下列方式:

  • 讀取每一行直至到達文件末尾
  • 在每一行我檢查字符串中的第三個字符是否等於1,如果第四個字符等於2,如果是我增加變量,這是我出生在十二月的人反,否則在下一個循環中執行

這裏是代碼:

int _tmain(int argc, _TCHAR* argv[]) 
{ 

    ifstream file("C:\\Kuba\\Studia & Nauka\\MATURA XDDD 
            \\INFA\\1\\Dane_PR\\pesel.txt"); 

    string line; 
    int bornInDecember=0; 

    if(!file.is_open()){ 

     cout << "Cannot read the file." << endl ; 

    }else{ 

     while(file.good()){ 

      getline(file, line); 

      if( line[2] == '1' && line[3] == '2' ){ 

       bornInDecember++ ; // 0-1 year, 2-3 month, 4-5 day 

      } 

     } 

     cout << "Amount of people born in december : "<< bornInDecember<< endl; 

     file.close(); 
    } 

    system("pause"); 

    return 0; 
} 

的問題是,我出現以下錯誤和我不知道爲什麼..

http://img10.imageshack.us/i/mvserr.png/

+0

行是空的,或者您正在訪問不存在的數據。 – DumbCoder 2011-03-28 10:58:18

回答

2

while file.good()是錯誤的 - getline仍然會失敗。你讀的文件,進程的最後一行它,file.good()仍然是真實的,那麼你嘗試讀取下一行和getline失敗。

你還需要檢查線夠長,你訪問line[n]之前 - 或者你會得到正是你得到的錯誤。

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    ifstream file("C:\\Kuba\\Studia & Nauka\\MATURA XDDD\\INFA\\1\\Dane_PR\\pesel.txt"); 
    string line; 
    int bornInDecember=0; 
    if(!file.is_open()){ 
     cout << "Cannot read the file." << endl ; 
    } else { 
     while (getline(file, line)) { // While we did read a line 
      if (line.size() >= 4) { // And the line is long enough 
      if( line[2] == '1' && line[3] == '2' ){ // We check the condition 
       bornInDecember++ ; // 0-1 year, 2-3 month, 4-5 day 
      } 
      } 
     } 
     cout << "Amount of people born in december : "<< bornInDecember<< endl; 
     file.close(); 
    } 
    system("pause"); 
    return 0; 
} 
1

之前,如果打印出來的線,看看它是否具有正確的價值,你也可以檢查線路的長度訪問之前:

std::getline(file, line); 
std::cout << line << std::endl; 
if(line.size() >= 4 && line[2] == '1' && line[3] == '2' ) 
... 

您還應該使用while(std::getline(file, line))代替while(file.good())

如果您編寫代碼,並且您希望某個值是特定的某個值,那麼可以使用斷言(如果該值不符合預期並且您立即捕獲該錯誤)。

#include <cassert> 
assert(line.size() == 10 && "line size is not equal to 10"); 
+0

你是對的檢查線的長度是至關重要的。 我檢查過.txt文件,每行都包含11位數字,但最後一行是空的,導致了這個問題。它現在有效,謝謝。 – koleS 2011-03-28 11:19:43

+0

@ user659389當你問一個問題時,如果你得到一個解決方案,不要忘了把答案放在正確的位置。 – hidayat 2011-03-28 12:23:44

0

嘛。很明顯,由於斷言消息狀態在程序中使用的std :: string下標超出了下標2(來自行[2])或下標3(來自行[3])的範圍。這意味着其中一行讀取的內容少於4個字符,因此您沒有第四個字符(行[3])。可能是如果文件尾隨,文件中可能爲空的最後一行。

由於陶菲克和Erik已經寫在自己的崗位上,你至少可以做的是檢查,如果線夠長。