Fixed integer overflow issue in shifting

This commit is contained in:
datalore 2023-10-27 16:43:19 +02:00
parent 8e0d2faefb
commit ca79610cfb
3 changed files with 9 additions and 6 deletions

View File

@ -10,10 +10,11 @@ void shift(char* text, int key)
std::cout << ' '; std::cout << ' ';
continue; continue;
} }
char c = std::tolower(text[i])-key; // has to be int, because the result can sometimes be > 127
int c = std::tolower(text[i])-key;
if(c < 'a') c+=26; if(c < 'a') c+=26;
if(c > 'z') c-=26; if(c > 'z') c-=26;
std::cout << c; std::cout << (char)c;
} }
std::cout << std::endl; std::cout << std::endl;
} }

View File

@ -20,10 +20,11 @@ int main(int argc, char** argv)
std::cout << ' '; std::cout << ' ';
continue; continue;
} }
char c = std::tolower(text[i])+key; // has to be int, because the result can sometimes be > 127
int c = std::tolower(text[i])+key;
if(c < 'a') c+=26; if(c < 'a') c+=26;
if(c > 'z') c-=26; if(c > 'z') c-=26;
std::cout << c; std::cout << (char)c;
} }
std::cout << std::endl; std::cout << std::endl;
return 0; return 0;

View File

@ -25,10 +25,11 @@ int main(int argc, char** argv)
std::cout << ' '; std::cout << ' ';
continue; continue;
} }
char c = std::tolower(text[pi]) + keyvalue(key[ki]); // has to be int, because the result can sometimes be > 127
int c = std::tolower(text[pi]) + keyvalue(key[ki]);
if(c < 'a') c+=26; if(c < 'a') c+=26;
if(c > 'z') c-=26; if(c > 'z') c-=26;
std::cout << c; std::cout << (char)c;
if(key[++ki] == 0) ki = 0; if(key[++ki] == 0) ki = 0;
} }
std::cout << std::endl; std::cout << std::endl;