2012-12-09 44 views
0

我有一個文本文件,上面寫着:首字符導致.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; 
+2

你能告訴我們調用'substr'的​​代碼嗎? –

+0

向我們顯示您正在使用的代碼 –

回答

1

很顯然,你的一個參數超出了引發out_of_range異常的範圍。我會運行一些測試,以確保值和s是你所期望的。

+0

在此while循環之前和之後沒有任何與我的問題有關的其他內容。其他一切都是聲明變量並打開文件。 – Archxiao

+0

謝謝你的說法,這讓我意識到我的問題是什麼! – Archxiao

+0

當然,您的歡迎 –