Program is skipping fgets without allowing input

前端 未结 2 1620
庸人自扰
庸人自扰 2021-01-22 05:15

Basically as the title says.. When my program is run from the console, it\'ll ask if you\'d like to encrypt or decrypt.. and when I input e or E, it creates a new blank line (un

2条回答
  •  感情败类
    2021-01-22 05:40

    The line scanf(" %c", &answer); is leaving a newline in the input buffer which is taken by fgets. The leading space in " %c" consumes leading whitespace but not trailing whitespace.

    You can get rid of the newline with the "%*c" format specifier in scanf which reads the newline but discards it. No var argument needs to be supplied.

    #include 
    
    int main(void)
    {
        char answer;
        char text[50] = {0};
        scanf(" %c%*c", &answer);
        fgets(text, sizeof text, stdin);
        printf ("%c %s\n", answer, text);
        return 0;
    }
    

提交回复
热议问题