c++ - 调试断言失败! (字符串下标超出范围)

标签 c++ visual-studio-2010 debugging

<分区>

好的。所以我正在制作一个简单的程序来试验字符串,并且在程序的一部分中,一个 for循环按顺序垂直显示字符串的每个字母。我正常运行该程序以检查其在整个编码过程中的进度,但是当我将其放入时,发生了错误。这是我的代码:

int main()
{
std::string word1 = "Chicken";
std::string word2("Nuggets");
std::string word3(3, '!');

std::string phrase = word1 + " " + word2 + word3;

std::cout << "The phrase is: " << phrase << "\n\n";

std::cout << "This phrase has " << phrase.size() << " letters!" << "\n\n";

std::cout << "The character at position zero is " << phrase[0] << "\n\n";

phrase[0] = 'S';

std::cout << "The phrase is now... " << phrase << "\n\n";

for (unsigned int i = 0; i <= phrase.size(); ++i)
{
    std::cout << "Position " << i << "'s character is " << phrase[i] << "\n";
}

}

非常感谢任何帮助,以及对我的代码的反馈(因为我是新手)。

附言<iostream><string>包括在内,我只是无法在
上向您展示它 网站。对不起!

最佳答案

for (unsigned int i = 0; i <= phrase.size(); ++i)

您将介于 0 和 phrase.size() 之间, 包括在内,太长了。你应该去phrase.size() - 1 .要么将其更改为那个,要么更改 <=<你应该没事。

示例修复 1:

for (unsigned int i = 0; i < phrase.size(); i++)

示例修复 2:

for (unsigned int i = 0; i <= phrase.size() - 1; i++)

编辑 - 更长/更详细的解释: 因为如果你有一个包含 5 个字母的字符串:“Hello”,你的实际索引是:

  • 字符串[0] = 'H'
  • 字符串[1] = 'e'
  • 字符串[2] = 'l'
  • 字符串[3] = 'l'
  • 字符串[4] = 'o'

这意味着 string[5] 在这种情况下走得太远了。由于您使用的是基于 0 的索引(与大多数编程语言一样),因此您必须从 0 到 size-1

关于c++ - 调试断言失败! (字符串下标超出范围),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24501443/

相关文章:

c++ - 警告 : returning reference to temporary

c++ - 从PPM文件加载的QImage无法正确显示

c# - 将 MS Access 数据库添加到 Visual Studio 2010 Express 中的项目

visual-studio-2010 - 团队基础服务器 : Creating UI components as part of code check-in

linux - Linux下如何将正在运行的C++进程堆转储到一个文件中?

c++ - mex 文件崩溃,如何在 matlab 中使用 MATLAB_MEM_MGR?

c++ - 递归检查父类(super class) type_info

c++ - 文件意外结束

c# - 在 visual studio 2015 中停止正在进行的调试

xcode - 如何快速检查Xcode 4.6.x中任意变量的值?