If statement being ignored in main function [duplicate]

社会主义新天地 提交于 2019-12-02 00:36:07

问题


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

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/29988637/if-statement-being-ignored-in-main-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!