Array Indexing Problems

Purpose of Program: To encrypt the user's string input by an increment of 1 character. Ex: if the user enters "Hello" the program encrypts it as "ifmmp"

Problem: It compiles perfectly, but when I try to run it the program acts like doesn't show the encryption. I believe that it has something to do with the key index, because whenever I try to put it as key[x + 1] or key[x + 2] it doesn't show anything, but when I tried key[x] it works. The problem with that is that I don't want the letters for the encrypted word to match the plain text word.


Does anyone know why this is happening? Any help is appreciated :]

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
#include<iostream>
#include<string>
using std::cout;
using std::endl;
using std::cin;
using std::string;

void main(){

	string proto = "Nothing";
	char key[27] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
	
	cout << "Word:";
	cin >> proto;
	
	int len = proto.length();
	int keylen = sizeof key;

	cout << endl;
	cout <<"- - - - - - - - - - - - - - - -" << endl;	
	for(int x = 0; x < len; x++){
		for(int y = 0; y < keylen; y++){
			if(proto[x] == key[y]){ proto[x] = key[y + 1];}
			else if(proto[x] != key[y]){;}
			} 
	cout << proto[x];
	}


	

}
Last edited on
1
2
3
4
for(int y = 0; y < keylen; y++){
    if(proto[x] == key[y]){ proto[x] = key[y + 1];}
    else if(proto[x] != key[y]){;}
}

Assume, proto[x] = 'a'. First it is compared to key[0], which is 'a'. Since 'a' == 'a', proto[x] is assigned key[1] which is 'b'. Now, on the second cycle proto[x] = 'b' is compared to key[1] = 'b'. Guess what happens..
The quick solution would be to add break after assignment. A much better one would be to realise that characters are numbers, and you can add 1 to them.
1
2
for( int i = 0; i < len; i++ ) proto[i]++;
cout << proto;


Note that this is no good, if you have 'z' in the string. Use if to fix that.
Topic archived. No new replies allowed.