Using scanf and fgets in the same program?

后端 未结 4 1227
盖世英雄少女心
盖世英雄少女心 2020-12-06 12:50

I need to do something like the following:

int main(void) {
char a,b,cstring;

printf(\"please enter something\");
scanf(\"%c %c\",&a,&b);
prinf(\"th         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 13:41

    The problem is when the flow reaches fgets(), this API first looks at stdin for input and it finds a stray '\n' there. As for fgets() which said that this API returns when it encounters EOF or '\n', since fgets() got '\n' from stdin so it executed without waiting for user to enter something as the APIs returning conditions met.

    Solution to the problem is that you use getchar(); after scanf and ignore the extra characters left by scanf(). e.g:

    scanf("%lf",&e);
    getchar();
    fgets(t,200,stdin);
    

    or

    other solution can be to use sscanf with fgets. e.g:

    #include 
    int main() {
    int j;char t[200];
    fgets(t,200,stdin);
    sscanf(t,"%d",&j);
    }
    

提交回复
热议问题