jonnyboy12 jonnyboy12 - 2 months ago 50
C++ Question

Encryption and decryption with ASCII in C++

As I am new to coding c++ and am taking a object oriented class, I need some help. For this code I want to encrypt it by shifting all of the text that is enter by 1 ascii digit i.e. a -> b, b-> etc. I am suppose to use all ascii values 32 - 126 but I cant figure out why when i try to encrypt anything I only get a "^" as a output.

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

void encrypt (string &encrypt)
{
string encryption;

for (int i = 0; i < encrypt.length(); i++)
{
encrypt[i]++;
if (i > 126){
encrypt = i - 94;
}
else if (i < 32){
encrypt = i + 94;
}
}
}

void decrypt (string decrypt)
{
string decryption;

for ( int i = 0; i < decryption.length(); i ++)
{
decryption[i]--;
if (i > 126){
decrypt = i + 94;
}
else if (i < 32){
decrypt = i - 94;
}
}
}

int main ()
{
string option;
string encryption1;
string decryption1;
cout << "Do you want to encrypt or decrypt? \n";
cin >> option;

if (option == "encrypt")
{
cout << "What do you want to encrypt \n";
cin.ignore();
cin.clear();

getline (cin, encryption1);
encrypt ( encryption1);
cout << encryption1 << " " << endl;
}

if (option == "decrypt")
{
cout << "What do you want to decrypt \n";
cin.ignore();
cin.clear();

getline (cin, decryption1);
encrypt ( decryption1);
cout << decryption1 << " " << endl;
}
return 0;**

Answer

I did something similar to this in my level one programming class last year. We created a Vigenere Cipher that is based off of the architecture of the Cesar cipher. Something that is useful is to first create a 0 base, i.e. if you are working with values a through b, subtract a from each of the characters that you are encoding first, do the math, double check that the value falls within the range of values (32 through 126 == 0 through 94) and then return the char + a. This would mean rewriting your logic and function to take a char instead of the entire string at once. As for why you are getting '^' as your only output, the ACSII code for '^' is 94 and your code:

for ( int i = 0; i < decryption.length(); i ++)
    {
        decryption[i]--;
        if (i > 126){
            decrypt  = i + 94;
        }
        else if (i < 32){
            decrypt = i - 94;
        }
    }
}

is setting the entire string to char 94. You set i = 0 then say that if i is less than 32 then the string decrypt is equal to the char 0 + 94 which is equal to 94 which is equal to '^'

Comments