If the operator is ignored in the main function

I am currently writing code in C and the if statement in the main function is being ignored. As you can see, this code takes some string as input and applies the Caesar cipher. Note. Also defined is an encryption function called main, I just don't insert 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 if the statement is completely ignored ( after writing "encrypt" the program just exits). The code is as follows:

int main()
{
    char text[SIZE], choice[SIZE];
    printf("\nWelcome to Caesar 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 Cipher:\n%s\n", text);
    }
    return 0;
}

      

+3


source to share


2 answers


The string that fgets

gets the terminator \n

at the end. You need to delete it manually or compare with"encrypt\n"



+4


source


Use this version strcmp()

:

if (strncmp(choice, "encrypt", 7) == 0)

      



The problem is that it fgets

preserves the newline character with your string, so to only compare the first N characters and leave it \n

out of comparison, use strncmp

to specify the number of characters you want to compare with

+2


source







All Articles