我从这里读到了关于substr的文章
http://www.cplusplus.com/reference/string/string/substr/
这是我的代码:
int main()
{
std::ifstream in ("c:\\users\\admin\\desktop\\aaa.txt");
std::ofstream out ("c:\\users\\admin\\desktop\\bbb.txt");
std::string s ;
while ( getline (in,s) )
{
std::size_t startpos = s.find("test");
std::string str = s.substr (startpos);
out << str << endl;
}
in.close();
out.close();
}
我收到错误:R6010 abort()被称为
注意:aaa.txt包含空格/字符/ html标记
有什么想法吗?
答案 0 :(得分:2)
由于我不知道文本文件的内容,您是否可以尝试进行以下更改,并让我知道错误是否仍然显示:
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
ifstream in("example.txt");
ofstream out("bbb.txt");
string s = std::string();
string str = std::string();
while (getline(in, s))
{
size_t startpos = s.find("test");
cout << s;
if (startpos != std::string::npos){
str = s.substr(startpos);
out << str << endl;
}
}
in.close();
out.close();
getchar();
return 0;
}
我正在使用if (startpos != std::string::npos)
条件检查查找成功时要执行的操作,这在代码中缺失。添加此案例将解决您的错误。
继续编码:)
答案 1 :(得分:0)
虽然Code Frenzy的回答是正确的,但您也可以使用例外来帮助捕获这些错误:
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
std::ifstream in ("aaa.txt");
std::ofstream out ("bbb.txt");
std::string s ;
try
{
while ( getline (in,s) )
{
std::size_t startpos = s.find("test");
std::string str = s.substr (startpos);
out << str << endl;
}
in.close();
out.close();
}
catch(std::exception e)
{
// (1) it will catch the error show show
cerr << e.what() << endl;
}
catch(std::out_of_range e)
{
// (2) this will also catch the same error if (1) was not there but could
// get you more details if you wanted since its more specific but i have
// not digged into it further
cerr << e.what() << endl;
}
catch(...)
{
// (3) just for sanity check if first two didn't catch it
cerr << "something went wrong";
}
}
exceptoin捕获此错误并打印消息:
无效的字符串位置