gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:50:59 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com