2012-12-09 39 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

当然,您的欢迎 –