Trouble returning a string

I am working on an assignment and though this is not a part of the assignment, this has piqued my interest.

1
2
3
4
5
6
7
8
9
10
11
12
13
string caesarCipher::encrypt(){

	string caesarEncrypt;

	cout<<"String to encrypt: ";
	cin>>caesarEncrypt;
	
	for (int i = 0; i < caesarEncrypt.length(); i++){
		caesarEncrypt[i] = caesarEncrypt[i] + shift;
	}

	return caesarEncrypt;
}


When I run the program, nothing for 'encrypt' is displayed. If I write cout<<caesarEncrypt, everything is good to go.

Can anybody tell me how to actually return the string? Thanks in advance to anybody who can help.
Something about the "+ shift" might be causing it. First is shift an int? if so you may need to this:

caesarEncrypt[i] = char( caesarEncrypt[i] + shift );
Shift is indeed an int. I tried your modification with no luck. Any other ideas out there? Any help would be appreciated.
closed account (zb0S216C)
If you want to return the string then try replacing your return statement with this:
 
return caesarEncrypt.c_str( );

Read about c_str( ) here: http://www.cplusplus.com/reference/string/string/c_str/
Your algorithm is wrong.
To implement the classic Caesar cipher on the english alphabet, do this:
1
2
if(isupper(caesarEncrypt[i]))caesarEncrypt[i] = (caesarEncrypt[i] - 'A' + shift)%26 + 'A';
else if(islower(caesarEncrypt[i]))caesarEncrypt[i] = (caesarEncrypt[i] - 'a' + shift)%26 + 'a';

You'll need ctype.h.
Last edited on
Topic archived. No new replies allowed.