Respuesta :
Answer:
#include <iostream>
#include <stdio.h>
#include <ctype.h>
using namespace std;
string
encrypt (string text, int s)
{ string resultingString = "";
for (int i = 0; i < text.length (); i++)
{ if (!isspace (text[i]))
{
if (isupper (text[i]))
resultingString += char (int (text[i] + s - 65) % 26 + 65);
else
resultingString += char (int (text[i] + s - 97) % 26 + 97);
}
else
{
resultingString += " ";
}
}
return resultingString;
}
string
decrypt (string text, int s)
{
string resultingString = "";
for (int i = 0; i < text.length (); i++)
{
if (!isspace (text[i]))
{
if (isupper (text[i]))
resultingString += char (int (text[i] + s - 65) % 26 + 65);
else
resultingString += char (int (text[i] + s - 97) % 26 + 97);
}
else
{
resultingString += " ";
}
}
return resultingString;
}
string upper(string str){
for (int i=0;i<str.length();i++){
str[i]=toupper(str[i]);
}
return str;
}
int
main ()
{
string text = "This is test text string";
int s = 3;
string cipherText = "";
string decipherText = "";
int menu=-1;
while (menu!=3){
cout<<"1. Encrypt"<<endl;
cout<<"2. Decrypt"<<endl;
cout<<"3. Exit"<<endl;
cin >>menu;
cin.ignore();
if(menu==1){
cout<<"Enter Plain string "<<endl;
getline(cin,text);
text=upper(text);
cipherText = encrypt (text, s);
cout << "cipher text: " << cipherText << endl;
}
else if(menu==2){
cout<<"Enter Encrypted string "<<endl;
getline(cin,cipherText);
cipherText=upper(cipherText);
decipherText = decrypt (cipherText, 26 - s);
cout << "decipher text: " << decipherText << endl;
}
else {
cout<<"Not valid"<<endl;
}
}
return 0;
}
Explanation:
Display menu with options 1 encrypt, 2 decrypt, 3 exit. Write a function to translate string to upper case. Iterate through string and for each index use toupper function to translate alphabet to upper case and store it back to current index of string.On exiting from loop return string. Pass upper case string to encrypt function.
In encrypt function pass string by reference and shift value. Create an empty string resultingString. Iterate through string for each character check if its space, if its a space add it to resulting string otherwise using ascii values convert char to its ascii add shift value and subtract 65 (staring ascii value for capital alphabet) take modules with 26 for new character and than add 65 to get alphabet.Now add this alphabet to resulting string. Upon loop completion return resultingString.
For decryption use same function as encryption. We are using cyclic property to decrypt using same function therefor subtract shift from 26 and pass resulting shift value to decrypt function.