Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

enter image description here

like image 958
Jaanus Avatar asked Jul 23 '26 14:07

Jaanus


2 Answers

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
like image 61
Armen Tsirunyan Avatar answered Jul 26 '26 07:07

Armen Tsirunyan


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.

like image 42
Ajay Avatar answered Jul 26 '26 06:07

Ajay