我有一个文本文件,内容如下:
this is an email file with DummyTest@my.test and some other text for the test
ATest@my.test
BTest@my.test
然后我有 a substr (s, e - s)
,其中 s 是行的开头, e 是结尾,这会给我这个:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_str`entering::substr
Aborted
这仅发生在底部两行,第一行将打印 DummyTest@my.test
我知道的问题是,当s
在行首并且之前没有字符(即“ATest@my.test”或“BTest@my.test”)时,会发生此错误。可以添加什么来防止这种情况发生?
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;