How to stop user entering char as int input in C

前端 未结 5 1554
北恋
北恋 2020-12-20 06:17

Heres a part of my code:

    printf(\"\\nEnter amount of adult tickets:\");
    scanf(\"%d\", &TktAdult);
    while (TktAdult<0){
        printf(\"\\n         


        
5条回答
  •  隐瞒了意图╮
    2020-12-20 06:54

    but how do I add to it so it also stops user from entering a char??

    You can't prevent user from entering character values. What you can do is check if tktAdult was successfully scanned. If not, flush out everything from stdin:

     bool valid = false;
     while (true) {
     ...
    
        if (scanf("%d", &TktAdult) != 1) {
           int c;
           while ((c = getchar()) != EOF && c != '\n');
        } else {
           break;
        }
    }
    

    The better alternative is to use fgets() and then parse the line using sscanf().

    Also see: Why does everyone say not to use scanf? What should I use instead?.

提交回复
热议问题