Program is skipping fgets without allowing input

一个人想着一个人 提交于 2019-12-02 01:01:59

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 <stdio.h>

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

From http://www.cplusplus.com/reference/cstdio/fgets/

"Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first."

Presumably you press Enter after typing E or D. Your scanf() doesn't consume the newline so it remains in the input stream. fgets() sees the newline and returns.

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