throwing an instance of 'std::out_of_range'

This program is removing the first two collumns of a text file.Does the job,but sometimes is giving me this error( I dont want to fix it with exeption handler)
terminate called after throwing an instance of 'std::out_of_range'
what (): basic_string::substr
Thanks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
using namespace std;
int main ()
{
    string line;
    remove("output.txt");
    ifstream infile("input.txt");
    fstream filestr;
    filestr.open("output.txt",fstream::in | fstream::out | fstream::app);
    while ( getline(infile, line) )
    {
        string out=line.substr(2,line.size());
        filestr<<out<<endl;
    }
    cout<<"DONE";
}
Last edited on
And given the fact that the exception occurs in string::substr, nothing in your code seems suspicious to you? You wouldn't, for instance, check to see if the range you're giving substr is inappropriate?
Error correcting the the most important part of any program. If you have a program that converts Celsius to Fahrenheit, then what would happen if your program got a letter instead of a number to translate? Error correcting is fixing these problems.

Your declaration of string out is the problem, what happens if line's length is 0? Does this mean your out variable will be declared with a -2 length? Doesn't seem good.

Error correction is what they don't seem to teach much in college these day but something businesses demand. Personally I think it should be something that is taught from the beginning once someone is taught Hello World!
why am I using size when I should be using:
1
2
3
4

string out = line.substr(2, line.length()-1);  // assuming I want the piece from 0,1,2 to end of 
// line, which would make the length 1 based and I need to make 0 based to prevent any errors.
You would get the same results with line.substr(2) ; the second parameter isn't needed when the substring should extend to the end of the original string. One could know this by looking at the documentation. William is on the right track, but it's the call to substr that causes the problem, not the definition of out.



Topic archived. No new replies allowed.