0

I had this problem before but went around it using other operator. But the same operator can't be used here I think (the getche();). Anyway this works well and good but if I input a letter it goes into an infinite loop.

printf("Enter the number of the passenger you wish to edit.");
scanf("%d", &userchoice);

do
{
    if(userchoice <= count || userchoice <= 1)
    {
        flag = 0;
    }
    else
    {
        printf("Please enter a valid input!");
        scanf("%d", &userchoice);
        flag = 1;
    }
} while (flag == 1);
undur_gongor
  • 15,657
  • 5
  • 63
  • 75

3 Answers3

2

You should see this answer :

https://stackoverflow.com/a/1716066/2263879

The problem is with your scanf.

Community
  • 1
  • 1
Sevauk
  • 56
  • 5
1

Yes , it will go into .

Since you are checking for userchoice<=1 , letter ascii value would be compared which will always be false and flag will always be 1

P.S: I am assuming count is pretty small number here , since you have not provided the value of it.

Srikanth
  • 447
  • 2
  • 8
  • the count is just a number of structs . no that not the currenbt problem the problem is that id u input something bad like a letter it goes into infiniteloop and out puts printf(please enter a valid input!) until it crashes and ignore the scanf – user3052741 Dec 04 '13 at 09:49
0

Do you mean userchoice between 1 and count, then the first if is incorrect. This code works, when you want to test in-between 1 and count.

    #include <stdio.h>
#include <ctype.h>

int main(int argc, char *argv[]) {
    signed int count = 5;

    signed int flag = 1;
    signed int userchoice = 0;

    printf("Enter the number of the passenger you wish to edit:");
    scanf("%d", &userchoice);

    do {
        if(userchoice <= count && userchoice >= 1) {
            flag = 0;
        } else {
            char c = '0';
            if (scanf("%d", &userchoice) == 0) {
                    printf("Please enter a valid input!\n");
              do {
                c = getchar();
              }
              while (!isdigit(c));
              ungetc(c, stdin);
            }
        }
    } while (flag == 1);

    printf("Done!");
}

Output:

a is not valid, because it is not a digit, 6 is bigger than count. 3 is possible and gets accepted.

Enter the number of the passenger you wish to edit:a
Please enter a valid input!
6
3
Done!
Binarian
  • 12,296
  • 8
  • 53
  • 84