C ++字符串操作,字符串下标超出范围

时间:2011-08-06 09:14:22

标签: c++ visual-studio string visual-c++

基本上应该做什么:

1)获取字符串并找到其长度

2)遍历key中的所有元素并将所有唯一成员放入start(playfair密码)

Table::Table(string key) {
    int i;
    for(i = 0; i < key.length(); i++) {
        if(start.find(key[i]) == string::npos) { //start is empty string
            start[start.length()] = key[i]; // this line gives error
        }
    }
}

错误:

enter image description here

3 个答案:

答案 0 :(得分:6)

因为有效索引的范围从0length - 1,包括start.push_back(key[i]); //this will increase the length by 1 。如果要在字符串中添加char,请使用push_back

{{1}}

答案 1 :(得分:1)

  

遍历key中的所有元素并将所有唯一成员放入start(playfair cipher)

您最好使用std::set<char>。而不是自己找到角色,只需使用set::insert方法。

稍后只需使用std::copyset的内容复制到string

答案 2 :(得分:-1)

违规行应为

start[start.length() - 1] = key[i];

字符串索引从0到(length() - 1)。