-1

I'm working on a practice program for encryption and decryption. I've recently been trying to teach myself C++, so please bear with me.

I want to read in a text file, ask the user how many characters he/she wants to rotate, and then rotate accordingly.

I've been running into a lot of problems while trying to do this. Finally, I have somewhat working code for this part.

My program now actually rotates and prints out the correct rotated character. However for some characters it is printing a } or even a Chinese character. I also have to rotate numbers for dates such as 2016 etc. I also have no spaces.

I know in my program I directly printing out ch, which is probably a big part of the error. I am not sure how to include spaces between the words and make sure it is using the correct rotated character.

I will post the function below. My program is a lot larger and I've been working on other parts but I won't post it all so it is more concise. Thank you in advance, I really appreciate the help. I've spent days trying to figure this out and certainly need the help.

Ryan Riis
  • 13
  • 5
  • I don't see any rotation. `'z' + rotNum` just rolls straight off the end... – John3136 Dec 07 '16 at 00:33
  • @john3136 Yes, that is part of my problem. It rotates, for example A to D if you rotate 3. But at the end it falls off. How do I fix that? – Ryan Riis Dec 07 '16 at 00:34
  • You should have an if statement checking if the words[i][j] + rotNum is between a and z. If it is then just set ch equal to that, if not then set ch equal (words[i][j] + rotNum) - 'a' (this assumes that rotNum is less than 26. If it is more than 26 set rotNum = rotNum % 26 this removes excess spins – Jesse Laning Dec 07 '16 at 00:37
  • `tolower(words[i][j])` is potentially UB, see https://stackoverflow.com/questions/21805674/do-i-need-to-cast-to-unsigned-char-before-calling-toupper – Baum mit Augen Dec 07 '16 at 00:37

1 Answers1

0

It looks to me that you need the modulus(%) operator. Something like this should work:

string rotEnc(int rotNum,vector<string> sentence) 
{
    stringstream ss;
    for ( int i = 0; i < sentence.size(); i++ ) 
    {
        for ( int j = 0; j < sentence[i].length(); j++ ) 
        {
            char c = tolower( sentence[i][j] );

            char ch = 'a' + ( ( rotNum + ( c - 'a' ) ) % 26 );
            ss << ch;
        }
        ss << ' ';
    }
    ss << ".\n";
}

To show the concept of single purpose, I made rotNum and the string vector parameters. The calling function should handle creating those. I also made it return the vector as a sentence.

tinstaafl
  • 6,908
  • 2
  • 15
  • 22