Reputation: 5795
I'm facing unexpected problem in my Caesar'c cipher. Caesar is when you encrypt text by shifting every letter by n numbers. So if it is 1, abc will be bcd. I work on the program that does that in C, but it works strange for some characters, regular letters, although it should be correct. Here is the problem syntax:
for (int i = 0; i < strlen(text); i++)
{
if (text[i] != ' ')
{
// printf("\n%i\n", key);
text[i] = text[i] + key;
if (text[i] > 122)
{
text[i] = text[i] + 97 - 122;
}
}
}
I wrap around by doing that math in the end. Can you please help me whats wrong with it?
EDIT: This code is fine, problem is with handling of command line parameters.
Upvotes: 1
Views: 533
Reputation: 9204
Use 96
in place of 97
problem solved
so when you wrap around then actually increase by 1 extra value think of this;
------------------------------------------
a | b | c | d | . . . x | y | z |
--------------------------------------------
97 | 98 | 99 | 100 | . . .120 | 121 | 122 |
-------------------------------------------
Try using 'a' , 'b' , .. .. .. ,'z' like this rather their actual values
using ' '
single quote inside char gives you integral value i.e. ASCII value
here is the code :
char c;
for (int i = 0; i < strlen(text); i++)
{
if (text[i] != ' ')
{
// printf("\n%i\n", key);
c=text[i];
text[i] = text[i] + key;
if(c >='a' && c <='z' && text[i] >'z')
text[i] = text[i] + 'a' -1 - 'z' ;
if(c >='A' && c <= 'Z' && text[i] > 'Z')
text[i] = text[i] + 'A' -1 - 'Z' ;
}
}
Upvotes: 2