If statement being ignored in main function [dupli

2020-04-11 12:45发布

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;
}

2条回答
做自己的国王
2楼-- · 2020-04-11 13:07

The string that fgets gets has a trailing \n in the end. You need to remove it manually, or compare it with "encrypt\n"

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-04-11 13:14

Use this version of strcmp():

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

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 , use strncmp to give the amount of chars you want to compare with

查看更多
登录 后发表回答