string - C++ Caesar Encryption Project (ASCII) -
for class, have develop caesar encryption project in c++ takes in string, , shifts ascii codes random integer. have project working perfectly, , code written below:
#include <iostream> #include <string> #include <stdlib.h> #include <time.h> using namespace std; int main(int argc, const char * argv[]) { string sentence = ""; int shifter, counter = 0, position = 0; srand(time(null)); shifter = (rand() % 25) + 1; cout << "enter sentence, , program encrypt it: " << endl; getline(cin, sentence); cout << "\n\n\n"; (int = 0; < sentence.length(); i++) { sentence[i] = sentence[i] + shifter; cout << sentence[i]; } return 0; }
my issue teacher wants them shifted letters. if letter 'z' , shift '2', wants output 'b'. not sure how done.
is simple procedure issue possible? if so, how done?
the first step realize letters need mapped numbers, rotated in way , mapped letters.
@vsoftco has tried on right track comments, read them because he's giving nice hints.
i try , fill in blanks @vsoftco has left out.
here how map letter number:
char letter = 'b'; int number = letter - 'a';
letters numbers computer knows represent letters. in fact letter 'b' 66 in ascii. if in c:
char letter = 'b'; int number = 100 - 'b'; // <- equal 100 - 66 34
number
becomes 34.
so nice want our numbers in range between 0 , 25 (so easy apply modulo operation).
think it. if add 5 unknown number between 0 , 25 how make sure result less 26? use modulo , wrap operation you.
but converting letters numbers. turn capital letter (note lower case letters have different numbers) number between 0 , 25 subtract 'a' this:
char letter = 'c'; int number = letter - 'a'; // <- 'c' - 'a' = 67 - 65 = 2 ( 3rd number if start counting 0 )
to convert numbers letters add 'a'.
int number = 5; // 6th letter since start counting 0 char letter = 'a' + number; // letter 'a' + 5 = 65 + 5 = 70 'f'...
with conversion , modulo operation @vsoftco described in comments should able make caesar algorithm on own.
Comments
Post a Comment