-2

I wrote this code, and all it meant to do is input ints until a negative is entered:

int result = 0, input_number = 0;
while(input_number >= 0){
    printf("Please enter students IDs(negetive to stop)= ");
    result = scanf("%d", &input_number);

    if(result != 1){
        printf("Invalid input! try again...\n");
        continue;
    }
}

When the input is an int- everything works fine,

But when entering a char (any char the is not int),

The loop becomes endlessly and scanf doesn't request any input anymore.

DO NOT suggest I use a replacement for scanf cause it's a work for school, and scanf must be used.

After entering char output:

Please enter students IDs(negetive to stop)= 4
Please enter students IDs(negetive to stop)= 5
Please enter students IDs(negetive to stop)= r
Please enter students IDs(negetive to stop)= Invalid input! try again...
Please enter students IDs(negetive to stop)= Invalid input! try again...
Please enter students IDs(negetive to stop)= Invalid input! try again...
Please enter students IDs(negetive to stop)= Invalid input! try again...
Please enter students IDs(negetive to stop)= Invalid input! try again...
Please enter students IDs(negetive to stop)= Invalid input! try again...
...

1 Answers1

0

Read a string, %s is format specifier, then convert to an int in your code. atoi() (or strtol() if you are C++) will work.

http://www.cplusplus.com/reference/cstdlib/atoi/ (C or C++)

http://www.cplusplus.com/reference/cstdlib/strtol/ (C++)

nicomp
  • 4,344
  • 4
  • 27
  • 60