2014-03-01 11 views
0

這不是作業,它是自學。我收到了一個意外的錯誤,認爲這是文件結束後getline請求的結果。我雖然我正在檢查,看看輸入是否成功與(while(getline(inf,mystring)),但它不工作。如果不是這種情況,我該如何有效檢查文件結尾?使用getline獲取文件輸入相關的運行時錯誤

這是我的代碼

#include <iostream> 
#include <string> 
#include <fstream> 
using namespace std; 

int main(int argc, char** argv) 
{ 
    string mystring, substring1 = "", substring2 = ""; 
    int sos; 
    ifstream inf (argv[1]); //open file for reading 
    if (!inf) 
    { 
     // Print an error and exit 
     cerr << "Uh oh, " << argv[1] << " could not be opened for reading!" << endl; 
     exit(1); 
    } 
     while(getline(inf,mystring)) 
     { 
       sos = mystring.find_first_not_of(" "); 
       if (sos != 0) 
       { 
        mystring = mystring.substr(sos, string::npos); 
       } 
       sos = mystring.find_first_of(" "); 
       if (sos != 0) 
       { 
        substring1 = mystring.substr(0,sos); 
        substring2 = mystring.substr(sos + 1, string::npos); 
       } 
       sos = substring2.find_first_of(" "); 
       if (sos != 0) 
       { 
        substring2 = substring2.substr(0, sos); 
       } 
       cout << substring2 << " " << substring1; 

     } 
    return 0; 
} 

這是錯誤

World Helloterminate called after throwing an instance of 'std::out_of_range' 
    what(): basic_string::substr 

這是輸入文件input.in

  Hello World 
+1

請使用調試器並將崩潰指向一行代碼。這應該會讓我們所有人的生活更輕鬆。 – Kelm

+0

文件中是否有空行? – herohuyongtao

+0

你究竟想要做什麼? – 0x499602D2

回答

1

之前提取的子字符串,需要檢查子字符串的範圍是否是物理的(也就是,對$ substr $的調用的第一個索引是否在最後一個)。我懷疑你的文件包含一個空行,在這種情況下,調用$ find_first_not_of $將返回$ npos $,表示在字符串結束之前沒有發現任何內容。

我建議增加一個支票$從$ find_first_not_of $ $返回非營利組織:

// Strip leading spaces 
sos = mystring.find_first_not_of(" "); 
/* sos == 0 would mean substr(0, npos) -> useless. 
    sos == npos would mean substr(npos, npos) -> un-physical. */ 
if (sos != 0 && sos != string::npos) 
{ 
    mystring = mystring.substr(sos, string::npos); 
} 

// Split string by first space 
sos = mystring.find_first_of(" "); 
substring1 = mystring.substr(0, sos); /* sos != 0, since strip leading spaces */ 
/* Check that sos+1 is inside the string. */ 
if (sos+1 < mystring.length()) 
{ 
    substring2 = mystring.substr(sos+1, string::npos); 
} 
else 
{ 
    substring2 = ""; 
} 

sos = substring2.find_first_of(" "); 
/* sos == 0 would cause substr(0, 0) -> un-physical, 
    sos == npos would cause substr(0, npos) -> useless. */ 
if (sos != 0 && sos != string::npos) 
{ 
    substring2 = substring2.substr(0, sos); 
} 

count << substring2 << ' ' << substring1 << std::endl; 
1

注意find_first_not_of返回字符串::非營利組織,當它沒有找到任何東西 - 不爲零,你正在測試。 如果你有沒有空格(或空行)的線路,然後你的find_first_not_of測試(」「)將返回字符串::非營利組織導致

mystring = mystring.substr(string::npos, string::npos); 

,這將導致異常。

相關問題