Reputation: 11
So I'm currently doing a caesar cipher program using the ASCII codes for the alphabet where the original text will shift 6 characters to the right but the problem is when I input the letter z, it returns Ç instead of returning the letter f. Here's my code so far:
void strEncrypt(string userin)
{
char wordArray[userin.length()];
strcpy(wordArray, userin.c_str());
for (int i=0; i<userin.size(); i++)
{
if(wordArray[i]>=65 && wordArray[i]<91)
{
wordArray[i] = wordArray[i] + 6;
if (wordArray[i]>90)
{
wordArray[i] = wordArray[i]-26;
}
}
else if(wordArray[i]>=97 && wordArray[i]<123)
{
wordArray[i] = wordArray[i] + 6;
while(wordArray[i]>=123)
{
wordArray[i] = wordArray[i]-26;
}
}
cout << wordArray[i];
}
}
Try to compile and run it so that you'll have a clearer picture of what my problem is
Upvotes: 1
Views: 132
Reputation: 4637
You're suffering from signed integer overflow!
A lot of this is implementation dependent/undefined behavior, but putting that aside I'm going to explain what happened.
Your char
type is signed, and holds values from -128
to 127
. 'z'
has a value of 122
. When you add 6
, it would become 128
... if it were capable of representing that number. However, the max value is 127
, and it overflows. It wraps around and becomes -128
.
You can put a check before the addition to make sure the character's value is low enough that you can safely increase it to avoid this problem.
Specifically, whether char
is signed or unsigned depends on the implementation, signed char
only needs to hold the values from -127
to 127
, and signed overflow is undefined behavior.
Upvotes: 2
Reputation: 4855
You have an overflow, using unsigned arithmetic fixes your code:
unsigned char wordArray[userin.length()];
strcpy((char *) wordArray, userin.c_str());
Upvotes: 0