R6010 abort() 已被调用

R6010 abort() has been called

我从这里读到 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 包含 spaces/characters/html 个标签

有什么想法吗?

由于我不知道文本文件的内容,您能否尝试进行以下更改并让我知道是否仍然显示错误:

#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) 条件来检查查找成功时要执行的操作,这在您的代码中缺失。添加此案例将解决您的错误。

继续编码:)

虽然 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 捕获此错误并打印消息:

invalid string position