I have a text file that reads:
this is an email file with DummyTest@my.test and some other text for the test
ATest@my.test
BTest@my.test
And then I have a substr (s, e - s), where s is the start of the line and e is the end that will give me this:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_str`entering::substr
Aborted
This only occurs for the bottom two lines, and the first will print DummyTest@my.test
The problem I know is what is happening is when s is at the beginning of the line and there are no characters before it (i.e. “ATest@my.test” or “BTest@my.test”), this error occurs. What could be added to prevent this from occuring?
while (getline(fin, lines))
{
for (int i = 0; i < lines.length(); i++)
{
if (lines[i] == '@')
{
int s;
if (i == 0 || i == 1) break;
for (s = i - 1; s < lines.length() ; s--)
{
if(validChar(lines[s]) == false )
{
s = s + 1;
break;
}
} //for
int e;
bool hasDot = false;
for (e = i + 1; e < lines.length(); e++)
{
if (e == lines.length()) break;
if(validChar(lines[e]) == false )
{
break;
} // if in for
if(lines[e] == '.') hasDot = true;
} // for
anEmail = lines.substr (s, e - s);
if (s < i && e > i && hasDot == true)
cout << anEmail << endl;
Obviously, one of your paramaters are out of range becase of the out_of_range exception that was thrown. I would run some test to make sure that the values s and e are what you would expect them to be.