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:
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).
精彩评论