Character string offset?

I am writing a program that solves Caesar ciphers in C ++. He takes the line of the alphabet and shifts it to the left each cycle: "abc .... yz" → "bcd ..... yza". The problem is the following loop: "bcd ..... yza" → "cde ..... yzaa".

char temp; // holds the first character of string string letters = "abcdefghijklmnopqrstuvwxyz"; while (true) { temp = letters[0]; for (int i = 0; i < 26; i++) { if (i == 25) { letters += temp; } letters[i] = letters[i + 1]; cout << letters[i]; } cin.get(); } 

Copy and paste this code and you will see what I'm talking about. How to fix this mysterious problem?

0
source share
3 answers

I think you need letters that should be 27 characters, not 26, but instead of letters += temp (which increments the line each time), use letters[26] = temp[0] .

... at this point you can completely stop temp :

 string letters = "abcdefghijklmnopqrstuvwxyz."; while (true) { letters[26] = letters[0]; for (int i = 0; i < 26; i++) { letters[i] = letters[i + 1]; cout << letters[i]; } cin.get(); } 

[edit]

Although a more natural way to deal with this is to use arithmetic for the characters themselves. The expression 'a' + ((c - 'a' + n) % 26) will shift a char c by n , placing Caesar's style.

+4
source

You can easily achieve this using valarray< char >::cshift(n) (cyclic shift).

+2
source

If I'm not mistaken, your loop will be exactly the same as the following code:

 letters = letters.substr(1,25) + letters.substr(0,1); // [skip 1, take 25] + [first char goes last] 
+2
source

Source: https://habr.com/ru/post/903665/


All Articles