Why the white spaces are ignored when converting to encrypted message?

Viewed 100

The Program should print the expected messages as expected but its not printing.

Plain Text message: Hello! how are you?

Expected encrypted message: Glqqv! bvc Rfl avm?

The program is printing: Glqqv!bvcRflavm

White spaces are totally ignored. How to fix it?

The Code:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string alphabet {"!A2BCDEFGHIJ@KLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"};
    string key {"!X2ZNLWEBGJHQDYVTK2F#UOMPCIASRxznlwebgjhqdyvtkfuompciasr"};

    string secret_message{};
    string encrypted_message{};

    cout << "Enter your secret message: ";
    getline(cin, secret_message);

    cout << "'nEncrypting message.... ";

    for (char c: secret_message)
    {
        float position = alphabet.find(c);
        if(position != string::npos)
        {
            char new_char {key.at(position)};
            encrypted_message += new_char;
        }
    }
    cout << "\n Encrypted message is: "<< encrypted_message << '\n';
    cout << "\n\n" << '\n';
    return 0;
}
2 Answers

' ' is not part key.

To handle c not found in key and remain unchanged, add an else statement.

    float position = alphabet.find(c);
    if(position != string::npos) {
        char new_char {key.at(position)};
        encrypted_message += new_char;
    } else  // add
        encrypted_message += c;
    }   

Recommend using type size_type as that is the type returned by .find() and used by .at().

    // float position = alphabet.find(c);
    std::string::size_type position = alphabet.find(c);

Float position = alphabet.find(c); //float is not making errors reading/printing the full line catch, but recommended you use an integer type instead.

Fix

size_t position = alphabet.find(c); //size_t fixed your issue an un-initialized int and You also forget to complete your if statement in the end by adding the function to set the position of encrypted_message to c as you assigned to be:

else encrypted_message += c;

for (char c: secret_message)
    {
    size_t position = alphabet.find(c); 
    if(position != string::npos) {
        char new_char {key.at(position)};
        encrypted_message += new_char;
    } else
        encrypted_message += c;
    }
Related