I'm helping a friend write a piece of code in C for an intro class that will take in a string and shift all of the characters of the string over by a certain amount of characters. So if he runs the program with the number 2, then it will shift all the characters over 2 places (hello -> jgnnq).
We're just trying to test for lowercase numbers now and no negative cases or anything like that. For some reason, this piece of code isn't working. We've just been testing with the letter o (ascii #111) and the number 18 for k. In the comments are our issues. I'm sure this is just some weird c behavior but we can't figure out what the problem is.
#include <string.h>
.
.
.
int k = atoi(argv[1]);
printf("Thanks for the %s. What sentence do you want to encrypt?\n", argv[1]);
string s = GetString();
for (int i = 0, n = strlen(s); i < n; i++) {
if (s[i] >= 'a' && s[i] <= 'z') {
// printing s[i] gives 111 for 'o'
// printing k gives 18
// printing s[i]+k gives 129 which is expected.
s[i] = s[i] +k;
// printing s[i] here should give 129 but it gives -127
while (s[i] > 'z') {
s[i] = s[i] -26;
}
}
}
Thanks!