0

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; 
1
  • encrypted is 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 to encrypted, or resize the string as needed BEFORE doing such assignments. Commented Jun 10, 2020 at 2:13

2 Answers 2

7

After string encrypted; encrypted is default-initialized as empty std::string which contains no elements. Then any access to non-existent elements like encrypted[i] leads to UB.

You can use push_back (or operator+=) instead.

//encrypting for (size_t i{}; i<message.length(); i++) { if (alphabet.find(message[i]) != string::npos) { pos = alphabet.find(message[i]); encrypted.push_back(key[pos]); } else { encrypted.push_back(message[i]); cout << encrypted[i]; } } 

Or initialize encrypted with message.length() elements in advance.

getline(cin,message); string encrypted(message.length(), '\0'); // initialize encrypted as containing message.length() elements with value '\0' //encrypting for (size_t i{}; i<message.length(); i++) { ... 
Sign up to request clarification or add additional context in comments.

Comments

1

from https://en.cppreference.com/w/cpp/string/basic_string/basic_string

Default constructor. Constructs empty string (zero size and unspecified capacity) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.