I am trying something simple in C, a program to get the exchange and do some conversions. To make sure scanf gets the right type I placed it into a while loop, which continues to ask for input until a number is inserted. If I enter a character instead of a number it does not ask again for an input.
exRate = 0;
scanfRes = 0;
while(exRate <= 0){
printf("Enter the exchange rate:");
while(scanfRes != 1){
scanfRes = scanf(" %f", &exRate);
}
if(scanfRes == 1 && exRate > 0){
break;
}
printf("Exchange rate must be positive.\n");
}
UPDATE: As this is a course assignment, I was not supposed to use anything outside of the taught material. When I asked the academic staff about handling unexpected input, I got an answer that this is a scenario I am not supposed to take into consideration.
The answers and help in the comments is all useful and I added 1 to all useful suggestions. The staff answer makes this question no longer needed.
scanfreturns1if it read successfully; or0if you entered a non-number, orEOFif the input was closed. The innermostwhileloop doesnt make any sensescanf()finds invalid input, it pushes back and returns prematurely. You have to consume the characters that are not numbers, otherwisescanfwill always be failing with the same erroneous input.