這不是作業,它是自學。我收到了一個意外的錯誤,認爲這是文件結束後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
請使用調試器並將崩潰指向一行代碼。這應該會讓我們所有人的生活更輕鬆。 – Kelm
文件中是否有空行? – herohuyongtao
你究竟想要做什麼? – 0x499602D2