c++ - 文本文件中的第一个字符导致 .substr() 错误

标签 c++ parsing substr

我有一个文本文件,上面写着:

this is an email file with DummyTest@my.test and some other text for the test
ATest@my.test
BTest@my.test

然后我有一个 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; 

最佳答案

显然,由于抛出的 out_of_range 异常,您的一个参数超出了范围。我会运行一些测试以确保值 s 和 e 是您期望的值。

关于c++ - 文本文件中的第一个字符导致 .substr() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13791602/

相关文章:

c++ - 将 Qt 添加到现有的 Visual Studio c++ 项目

xml - 使用命名空间访问 XML 属性

parsing - 消除此 PEG.js 语法上的左递归

c++ - 在哪里可以找到所有数学函数的描述,比如 floorf 和其他函数?

c++ - 父类和子类之间的静态变量

c++ - 套接字编程学习

python - 如何使用 python 提高解析器的速度?

oracle - 带有 substr 的多个 CASE/WHEN

MySQL 在 SELECT 中提取多个子字符串,任意次数

java - 从字符串中获取不同数字的列表