尝试对角显示字符串时出现 C++ 程序崩溃

I am getting a c++ program crash when trying to display a string diagonally

当我 运行 我的程序崩溃时,我 运行 调试器并报告: std::out_of_range 在内存位置 0x0066F6F4。

我的代码如下:

#include <iostream>
#include <string>

int main() {
    std::string name = "Alexi";

    for (unsigned int i = 0; i <= name.length(); i++) {
        for (unsigned int x = 0; x <= i; x++)  {
            if (i == x) std::cout << name.at(x);
            else std::cout << " ";
        }
        std::cout << '\n';
    }

    return 0;
}

如有任何帮助,我们将不胜感激。

你应该 i < name.length() 而不是 i <= name.length()

#include <iostream>
#include <string>

int main() {
    std::string name = "Alexi";

    for (unsigned int i = 0; i < name.length(); i++) {
        for (unsigned int x = 0; x <= i; x++)  {
            if (i == x) std::cout << name.at(x);
            else std::cout << " ";
        }
        std::cout << '\n';
    }

    return 0;
}

字符串 name 的长度为 5。

在内部,它存储在一个名为 namechar [](字符数组)中,其中

  • 字符A存储在name[0]
  • 字符l存储在name[1]
  • 字符e存储在name[2]
  • 字符x存储在name[3]
  • 字符i存储在name[4]

所以请注意,长度是 5,但您的 最大索引是 4。

这是因为 C 和 C++ 数组是 0-indexed