C++ Terminate has called after throwing an instance of 'std::out_of_range' -


i have tried countless times solve , nothing on internet helping. i've figured problem "getline(cin,strg);" dont know what, program runs if use "cin >> strg;", however, want account spaces , whatnot. problem?

#include <iostream> #include <stdlib.h> using namespace std;  string alphabet = "abcdefghijklmnopqrstuvwxyza"; string alphacap = "abcdefghijklmnopqrstuvwxyza"; int loc;  string code(string str) {     for(int = 0; <= str.length()-1; i++){         if(alphabet.find(str[i]) != str.npos){             loc = alphabet.find(str[i]);             str = str.substr(0,i) + alphacap[loc+1] + str.substr(i+1,str.length());         }     }     return str; }  string decode(string str) {     for(int = 0; <= str.length()-1; i++){         if(alphabet.find(str[i]) != str.npos){             loc = alphabet.find(str[i]);             str = str.substr(0,i) + alphacap[loc-1] + str.substr(i+1,str.length());         }     }     return str; }   int main() {     string codc;     do{         system("cls");         cout << "code or decode? ";         cin >> codc;     }while(codc != "code" , codc != "code" , codc != "decode" , codc != "decode");      string str;      if(codc == "code" or codc == "code"){         string strg;         getline(std::cin,strg);         cout << code(strg);     }else{         string strg;         getline(cin,strg);         cout << decode(strg);     }  } 

the exception caused by:

str.substr(i + 1, str.length()); 

as tries access str's elements i + str.length(). fails i > 0. see original q&a.

str.substr(i + 1, str.length() - - 1); correct it.

if want part of string on right of index i, can leave out second argument:

str.substr(i + 1); 

see reference.

and dangerous too:

alphacap[loc + 1] alphacap[loc - 1] 

what if loc index of first/last element in alphacap?


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -