字符串下标超出范围C++:调试
String Subscript Out Of Range C++: Debug
所以我正在调试一个运行时错误。"字符串下标超出范围"。
我知道问题出在哪里,是什么原因造成的,但我正在寻找一种可能的解决方案,它将以类似或相同的方式运行,而不会给我错误。
以下是错误发生位置的代码片段。如果我错了,请纠正我,因为我声明了一个0长度的字符串,然后试图操作第n个元素,所以出现了问题。
std::string VsuShapeLine::GetRunwayNumber()
{
std::string name, nbstr, newnbstr, convnbstr;
int idx,idx2, num, count, pos;
char buf[3];
int idx3=-1;
name = this->GetName();
idx = name.find("ALight");
if (idx == -1)
{
idx = name.find("Lights");
idx3 = name.find_last_of("Lights");
}
idx2 = name.find('_');
idx2 +=3;
nbstr = name.substr(idx2, idx-idx2);
if (idx3 != -1)
idx3++;
else
idx3 = idx+6;
if (name.at(idx3) == 'N')
{
pos = nbstr.length();
if (isalpha(nbstr[idx-1]))
nbstr[pos-1] = _toupper(nbstr[pos-1]);
return (nbstr);
}
else if (name.at(idx3) == 'F')
{
convnbstr = nbstr.substr(0,2);
num = atoi(convnbstr.data());
num +=18;
_itoa(num, buf, 10);
newnbstr = buf;
count = nbstr.size();
if (count > 2)
{
if (nbstr.at(2) == 'l' || nbstr.at(2) == 'L')
newnbstr += 'r';
else if (nbstr.at(2) == 'r'|| nbstr.at(2) == 'R')
newnbstr += 'l';
else if (nbstr.at(2) == 'c' || nbstr.at(2) == 'C')
newnbstr += 'c';
}
pos = newnbstr.length();
if (isalpha(newnbstr[pos-1]))
newnbstr[pos-1] = _toupper(newnbstr[pos-1]);
return (newnbstr);
}
return ("");
}
Btw对于感兴趣的人来说,问题在这一行:
if (isalpha(nbstr[idx-1])
在这一点上,nbstr是一个长度为3的字符串,idx的值(我的程序的工作方式)总是9或10。
正如退役忍者提到的,应该在使用字符串::find函数后进行检查。
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 在linux上调试巨大的C++项目
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 如何针对特定情况调试和修复此双自由内存损坏问题
- 正在VS调试器中监视映射条目
- 使用调试/崩溃报告将应用程序部署到客户端
- VC++本机单元测试,找不到调试符号
- 如何在C++生成器中禁用"使用调试.dcus"
- 使用vscode调试时,GDB意外退出
- 即使使用调试编译标志,表达式也是"optimized out"
- 调试 CUDA MMU 故障
- 小字符串优化(调试与发布模式)
- 调试和自由执行中的信号处理
- 调试编译的服务器在数据库打开时崩溃
- Visual Studio 调试优化如何工作?
- 如何配置Visual Studio Code以使用cygwin,cmake和gcc进行调试
- 从 exe 文件 (Visual Studio ) 启动时调试断言失败
- 如何在大型c++项目的可视化代码中设置调试
- Qt 调试显示行号
- 如何将可变参数模板转换为多个单个模板?(C++竞争编程调试模板)