R6010 abort() has been called

我的未来我决定 提交于 2019-12-24 04:05:09

问题


I read about substr from here

http://www.cplusplus.com/reference/string/string/substr/

Here is my code :

 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();
}

I get error : R6010 abort() has been called

Note : aaa.txt contains spaces/characters/html tags

Any idea ?


回答1:


Since I dont know the content of the text file, could you try making the following changes and let me know if the error is still being shown:

#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;
}

I am using if (startpos != std::string::npos) condition to check what to do when the find succeeds, this is missing in your code. adding this case will resolve your error.

Keep coding :)




回答2:


While Code Frenzy answer is right, you can also use exceptions to help catch these kind of errors:

#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";
    }
}

The exceptoin catches this error and prints the message:

invalid string position



来源:https://stackoverflow.com/questions/28136617/r6010-abort-has-been-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!