开发者

C++ string manipulation, string subscript out of range

Basically what this should do:

1) gets string and finds its length

2) goes throught all elements in key and puts all unique members in start (playfair cipher)

开发者_运维问答
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
        }
    }
}

error:

C++ string manipulation, string subscript out of range


Because the valid indices range from 0 up to length - 1 inclusive. If you want to add a char to the string, use push_back

start.push_back(key[i]); //this will increase the length by 1


goes throught all elements in key and puts all unique members in start (playfair cipher)

You should better be using std::set<char>. And instead of finding the characters yourself, just use set::insert method.

Later just use std::copy to copy the contents of set to string.


The offending line should be

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

String indices go from 0 to (length() - 1).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜