Caesar Cipher Encryption

How would I get my for loop to go back to my starting value on the ASCII table? Since the user can use any characters in the range of 33-122 on the ASCII table, how would I get my code to shift back to 33 if it surpasses 122?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
  #include <iostream>
#include <string>

using namespace std;

int main() 
{
	string userPass;
	int userKey;
	
	cout << "Enter a password that is at least 8 characters long: ";
	cout << endl;
	getline(cin, userPass);
	
	while(userPass.length() < 8)
	{
		cout << "\nThe password must be at least 8 characters long. Try again.\n";
		getline(cin, userPass);
	}
	
	cout << endl;
	
	cout << "Please enter a key between numbers 1 - 10 inclusive: ";
	cout << endl;
	cin >> userKey;
	
	while(userKey < 1 || userKey > 10)
	{
		cout << "\nThe key must be between 1 and 10, you entered " << userKey << ". Try again.\n";
		cout << endl;
		cin >> userKey;
	}
		
	int n = userPass.length(); 
		
	for (int i = 0; i < n; i++)
	{
			int offset = 122;
			int cipheredLetter = (((int)userPass[i] - offset + userKey) % 33) + offset;
		
			cout << (char)cipheredLetter;
	} 
		
}



The sample answer is: Your password is letmeinz the encrypted version of your password is rkzskot& with a key of 6.

When I run my code I get a Ç instead of &.
Since the user can use any characters in the range of 33-122 on the ASCII table, how would I get my code to shift back to 33 if it surpasses 122?
Probably the easiest fix would be that the number you modulo should correspond to the range of inputs. So if 33-122 (inclusive?) is valid, that's a total of 122-33+1 values, so you should do mod (122-33+1) and then offset it by 33 after the mod.
@iiAlex

This for loop.. (lines 36 to 42)
1
2
3
4
5
6
7
for (int i = 0; i < n; i++)
	{
			int offset = 122;
			int cipheredLetter = (((int)userPass[i] - offset + userKey) % 33) + offset;
		
			cout << (char)cipheredLetter;
	}


could be changed to..
1
2
3
4
5
6
7
8
for (int i = 0; i < n; i++)
	{
			int offset = 122;
			int cipheredLetter = (((int)userPass[i] - offset + userKey) % 33) + offset;
		if(cipheredLetter>122) // Added this line
		  cipheredLetter = 32+userKey; // And this one
			cout << (char)cipheredLetter;
	}


You could make line 43 to be cout << endl; so the ending text is on a separate line. Aesthetics, really.
Last edited on
Topic archived. No new replies allowed.