【发布时间】:2013-12-11 17:05:33
【问题描述】:
所以我正在调试我遇到的运行时错误。 “字符串下标超出范围”。
我知道问题出在哪里以及导致问题的原因,但我正在寻找一种可能的解决方案,该解决方案将以相似或相同的方式执行而不会出现错误。
这是发生错误的代码 sn-p。如果我错了,请纠正我,出现问题是因为我声明了一个长度为 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 ("");
}
【问题讨论】:
-
也许您可以向我们展示
idx的设置,因为这似乎是您的问题。 -
如果这是你的全部代码并且字符串确实是空的,你不能索引到它。
-
你....在声明它和尝试索引它之间对
nbstr做任何事情吗?如果pos为0,那么nbstr[pos-1]肯定会让运行时开始运行。 -
是的,在声明和其他 3 行之间有一个完整的函数,我应该发布整个内容吗?
-
是的,发布所有相关代码。
标签: c++ string debugging assertions