Validating input using scanf's return value isn't working

醉酒当歌 提交于 2021-02-08 05:13:26

问题


I'm working on a tic-tac-toe final project. I ask the user to print the box number he would like to fill in, and then i use integer err to obtain the return value of scanf. Scanf should return the number of integers it has read in this case, and I am asking for one integer to be read, so as long as err != 1, it should go into the while loop. This, however, isn't working.


        printf("\nBox number: ");
        int boxNumber, err;
        err = scanf("%d", &boxNumber);

        while (err != 1) {
            printf("\nWrong input.");
            printf("\nBox number: ");
            err = scanf("%d", &boxNumber);
        } 

When a non-integer is inputted, the output is:

Wrong Input.
Box number:

In a non-stop loop. The line where scanf is then called again for the user to input a value is as though never run.
I have no idea what the problem is. Please help.


回答1:


After the first scanf() fails, the non-integer remains in the input stream and prevents any following from succeeding, while staying forever.

You need to get rid of the non-scannable lingering input.

See these articles for choosing your favorite method:
http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
How to read / parse input in C? The FAQ



来源:https://stackoverflow.com/questions/50272231/validating-input-using-scanfs-return-value-isnt-working

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