#include<stdio.h>
int main()
{
int amount,i;
char message[81],encry[81];
printf("Enter message to be encrypted : ");
gets(message);
printf("Enter shift amount (1-25) : ");
scanf("%d");
for(i=0;message!='\0';i++)
{
if(message[i] >='A' && message[i] <='Z')
encry[i]=((message[i]-'A')+amount)%26+'A';
}
printf("Encrypted message : ");
int j;
for(j=0;message[j]!='\0';j++)
printf("%c",encry[j]);
return 0;}
I try to write a caesar cipher code but it can not run. Please help me. Thank you.
1 .
printf("Enter shift amount (1-25) : ");
scanf("%d");
^ missing variable here (you need to pass an argument of type int *)
Where will you take input key then ?
You need to take input in amount
variable like this -
printf("Enter shift amount (1-25) : ");
scanf("%d",&amount);
So , you don't store anything in amount
and it is uninitialized .And you use it , therefore it causes undefined behaviour.
2. In this loop -
for(i=0;message!='\0';i++) // you compare here char * with char
condition should be -
for(i=0;message[i]!='\0';i++)
3. Don't use gets
to take input, it won't prevent overflow . Use fgets
-
fgets(message,81,stdin);
Error in scanf("%d")
syntax it has to be like scanf("<format specfier>",&variable);
So the fix is scanf("%d", &amount)
int j;
is not a good practice to add the variable before for loop.
Problems:
Here:
scanf("%d");
The %d
requires a second argument(of type int*
) for storing the scanned number. You probably wanted:
scanf("%d", &amount);
You are comparing a char
and a char*
here:
for(i=0;message!='\\0';i++)
You probably wanted
for(i = 0; message[i] != '\\0'; i++)
Don't use gets()
as it is deprecated. Use fgets
instead:
fgets(message, sizeof(message), stdin);
Note that fgets
consumes the newline character and stores it in message
(if there is space).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.