我有一個文本文件,上面寫着:首字符導致.substr()錯誤
this is an email file with [email protected] and some other text for the test
[email protected]
[email protected]
然後,我有一個substr (s, e - s)
,其中s是線路和e的開局到底該會給我這樣的:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_str`entering::substr
Aborted
這隻發生在底部兩行,第一個將打印[email protected]
我知道發生了什麼事時s
是t的問題他開始行並且在它之前沒有字符(即, 「[email protected]」或「[email protected]」),則會發生此錯誤。可以添加什麼來防止發生這種情況?
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;
你能告訴我們調用'substr'的代碼嗎? –
向我們顯示您正在使用的代碼 –