I'm currently writing a code in C and my if statement in main function is being ignored. As you can see, this code receives some string as input and applies the Caesar's Cipher. Note: Function ciphering called in main is also defined, I just don't paste because I don't think it is necessary because the problem is that when I ask the user if he wants to encrypt or decrypt the text, after fgets the if statement is completely ignored (after writing "encrypt" the program just quits). The code is the following:
int main()
{
char text[SIZE], choice[SIZE];
printf("\nWelcome to Caesar's Cipher.\nDo you wish to encrypt or decrypt text?\n");
fgets(choice, SIZE, stdin);
if (strcmp(choice, "encrypt") == 0)
{
printf("Insert text to encrypt:\n");
fgets(text, SIZE, stdin);
ciphering(text);
printf("\nThis is your text encrypted with Caesar's Cipher:\n%s\n", text);
}
return 0;
}
The string that
fgets
gets has a trailing\n
in the end. You need to remove it manually, or compare it with"encrypt\n"
Use this version of
strcmp()
:The problem is that
fgets
stores the newline character with your string, so to take only the first N characters to compare and leave the\n
out of the comparison , usestrncmp
to give the amount of chars you want to compare with