在我的程序的这一部分中,我想去掉字符串 highScore 中的前导 0。这是我所拥有的(不是整个程序;这只是我遇到问题的部分):
//take out leading 0s
for (int i = 0; highScore.at(i) != '\0'; i++)
{
if (highScore.at(i) == '0')
highScore = highScore.erase(0, 1);
else
break;
}
highScore 字符串中包含字符串“000500000”,因此在变量 i 变为 3 后,它应该离开循环(至少,这就是我想要的),而是继续循环遍历字符串 2更多次,然后输出此错误:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at: __n (which is 5) >= this->size() (which is 4)
我对此有点困惑,因为我认为我没有做任何会使字符串超出范围的事情。
最佳答案
您既缩短了字符串,又推进了下标。这很快就会让你出界。您的 if
应始终测试 .at(0)
,并且您的循环(如上面其他人所述)应测试 size()。您无法使用 '\0'
查找结尾。
关于c++ - 为什么我的 if 语句在应该评估为 false 时却没有评估为 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66166621/