C - User input getting skipped?

后端 未结 2 1561
死守一世寂寞
死守一世寂寞 2020-12-21 05:07

I want a menu from which you choose some action.

Problem is that when we choose one, and press the \"return\" key, the user input command which should have been the

2条回答
  •  情话喂你
    2020-12-21 05:20

    scanf() leaves a newline which is consumed by the subsequent call to gets().

    Use getchar(); right after scanf() or use a loop to read and discard chars:

    int c;
    while((c= getchar()) != '\n' && c != EOF); 
    

    I know you have commented about gets() being bad. But you shouldn't even attempt to use it even if it's a toy program. It's been removed from the latest C standard (C11) completely and shouldn't be used even if you are programming for C89 (due to its buffer overflow vulnerabilities). Use fgets() which does almost the same except possibly leaves a trailing newline.

    If this is your complete code, then you would also need a prototype or at least a declaration for do_this(). Implicit int rule has also been removed from C standard. So add,

    int do_this();
    

    at the top of your source file.

提交回复
热议问题