c++ - 字符串下标超出范围错误

标签 c++ string

嘿,我对这段代码有疑问。我已经阅读了一些关于它的问题,但我在我的代码中找不到问题。如果可以,请帮助我。

#include <iostream>
#include <conio.h>
#include <string>

using namespace std;

int main()
{

    cout << "You have 20 attempts";
    string slowo="program";
    char litera;
    unsigned j=0;

    for(int i=0;i<20;i++)
    {
        if (j > slowo.size())j=0;

        litera = _getch();
        for(unsigned z=0;z < slowo.size();z++)
        {
            if (litera==slowo[j])
            {
                cout << slowo[j];
                break;
            }
            else cout << "-";
        }
        //cout << litera;

            j++;
    }getch();
}

当我没有数组时,我忘记了字符串的那个小东西。

最佳答案

你正在读取 slowo 中的索引 slowo.size(),但是下标是从 0 开始的,所以 slowo 只能被索引从 0slowo.size()-1。您需要将您的条件更改为

if (j >= slowo.size())j=0;

关于c++ - 字符串下标超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19317682/

相关文章:

swift - 比较当前日期与编码字符串

javascript - 有没有一种方法可以缩短字符串唯一 ID 数组,同时仍确保唯一性?

php - 如何检查字符串的字符集?

c++ 对日期进行二分搜索排序 -> 我需要一个范围(cca)

c++ - 未知类型名称 'class' ;你是说 'Class' 吗?奥里奥触控

c++ - 在 C++ 中创建结构数组

string - 当虚拟对象具有指定长度时将字符串作为参数传递

c++ - iOS:添加C++静态库后应用体积太大?

c++ - 优化三元算子

c - 当放入c中的数组时,字符串会变形