C - User input getting skipped?

后端 未结 2 1563
死守一世寂寞
死守一世寂寞 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:32

    scanf("%d",&choice);
    

    This leaves the newline ('\n') in the standard input buffer stdin.

    Your call of gets() merely consumes that whitespace, writing nothing into name.

    To prevent this, consume the newline char after you call scanf, for instance by using getchar(). If you are not on a microsoft platform, please do not use fflush(stdin), as that is undefined behavior (on non-MS platforms).

提交回复
热议问题