这不是功课,而是自学。我收到一个意外错误,认为是文件结束后getline请求的结果。我虽然正在检查while(getline(inf,mystring))输入是否成功,但无法正常工作。如果不是这种情况,如何有效检查文件结尾?
这是我的代码
#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
最佳答案
在提取子字符串之前,需要检查子字符串的范围是物理范围(即,对$ substr $的调用的第一个索引位于最后一个索引之前)。我怀疑您的文件包含空行,在这种情况下,对$ find_first_not_of $的调用将返回$ npos $,指示在字符串末尾之前未找到任何内容。
我建议添加一张从$ find_first_not_of $返回的$ npos $支票:
// 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;