I am trying to make and extended version of Caesar Cipher including all the 7 bit ASCII characters that's for ASCII values 32 (which is a space) to 126 (which is a tilde), but the problem is how can I make sure that my program uses only those ASCII characters and not jump into using the weird DEL symbol or the extended ASCII chart.
For ex - if I type the lowercase "u" and input 10 as for the key I will get del symbol, but I want to get a space when I type lowercase "u"
This is the code I have so far
#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
using namespace std;
string Encrypt(string, int);
int main(int argc, char *argv[])
{
string Source;
int Key;
cout << "Source: ";
getline(cin, Source);
cout << "Key: ";
cin >> Key;
cout << "Encrypted: " << Encrypt(Source, Key) << endl;
system("pause");
}
string Encrypt(string Source, int Key)
{
string Crypted = Source;
for (int Current = 0; Current < Source.length(); Current++)
Crypted[Current] += Key;
return Crypted;
}
Simple: Just copy any input values outside the blessed range without modification, you just need two comparisons:
if(x<' ' || x>126)
copy();
else
encode();
The algorithm for caesar cipher is:
Aside: You might have to map the key before application too.
ok i found it what i did was just modify the formula to force the program to loop through ASCII values 32 - 126,
Crypted[Current] = ((Crypted[Current] + key) - 32) % 95 + 32;(Encrypting)
Crypted[Current] = ((Crypted[Current] - key) - 32 + 3 * 95) % 95 + 32; (Decrypting)
thanks Greg for the idea
this is the complete code working prefectly
#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <cmath>
using namespace std;
string encrypt(string, int);
string decrypt(string source, int key);
int main(int argc, char *argv[])
{
string Source;
int Key;
cout << "Source: ";
getline(cin, Source);
cout << "Key: ";
cin >> Key;
cout << "Encrypted: " << decrypt(Source, Key) << endl;
system("pause");
}
string encrypt(string source, int key)
{
string Crypted = source;
for (int Current = 0; Current < source.length(); Current++)
Crypted[Current] = ((Crypted[Current] + key) - 32) % 95 + 32;
return Crypted;
}
string decrypt(string source, int key)
{
string Crypted = source;
for (int Current = 0; Current < source.length(); Current++)
Crypted[Current] = ((Crypted[Current] - key) - 32 + 3 * 95) % 95 + 32;
return Crypted;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.