Tharwat Harakeh
Tharwat Harakeh

Reputation: 89

R6010 abort() has been called

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 ?

Upvotes: 2

Views: 13500

Answers (2)

zar
zar

Reputation: 12227

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

Upvotes: 0

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 :)

Upvotes: 2

Related Questions