The cout of encrypted string doesn't show anything and sometimes the program crashes. And when i do cout << encrypted[i] in for loop , i got the correct result. Also if i do a for loop to read string char by char for(char c:encrypted) , cout << c << endl; => it doesn't work also and got garbage.
#include <iostream> #include <string> using namespace std; int main() { string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; string key = "XZNLWEBGJHQDYVTKFUOMPCIASRxznlwebgjhqdyvtkfuompciasr"; string encrypted; string decrypted; string message; int pos{}; cout << "enter the message" << endl; getline(cin,message); //encrypting for (size_t i{} ;i<message.length();i++) { if (alphabet.find(message[i]) != string::npos) {pos = alphabet.find(message[i]); encrypted[i] = key[pos]; }else {encrypted[i]=message[i]; cout << encrypted[i]; } } cout << "the encrypted message is: "<< encrypted << endl;
encryptedis initialised as an empty string.encrypted[i] = key[pos]does not change that - in fact it gives undefined behaviour. Lack of output is only one possible symptom - your code may be writing to random memory. Either append characters needed toencrypted, or resize the string as needed BEFORE doing such assignments.