I've written a function getIntLimited that asks the user to input a valid integer between 10 and 20 and getIntLimited calls a function getInt to confirm if the input is a valid integer. Everything works as intended expect for if the user actually inputs a valid integer that is between 10 and 20. It will simple proceed to a blank newline to scan another input instead of outputting the printf statement ("You entered: %d \\n", iVal);
I'm not sure why it doesn't output the printf statement when the conditions are met. Here's my code:
#include <stdio.h>
#include <stdlib.h>
//tools
void flushKeyboard(void);
void pause(void);
int getInt(void);
int getIntLimited(int lowerLimit, int upperLimit);
double getDoubleLimited(double lowerLimit, double upperLimit);
//app interface
int main(void){
flushKeyboard();
pause();
int answer;
printf("Enter an integer: ");
answer = getInt();
printf("You entered: %d \n", answer);
int iVal;
printf("Enter an integer between 10 and 20: ");
int lowerLimit = 10;
int upperLimit = 20;
iVal = getIntLimited(lowerLimit, upperLimit);
printf("You entered: %d \n", iVal);
return 0;
}
//code your functions here:
void flushKeyboard(void)
{
int read;
while (( read = getchar()) != '\n' && read != EOF) {
continue;
}
return;
}
void pause(void)
{
printf("Press <ENTER> to continue...");
flushKeyboard();
return;
}
int getInt(void)
{
int Value;
char NL = 'x';
while (scanf("%d%c", &Value, &NL) != 2 || NL != '\n') {
flushKeyboard();
printf("Invalid integer, please try again: ");
}
return Value;
}
int getIntLimited(int lowerLimit, int upperLimit)
{
int limit;
do {
limit = getInt();
if(lowerLimit > limit || upperLimit < limit) {
printf("Invalid value, %d < %d < %d: ", lowerLimit, limit, upperLimit);
}
}while(lowerLimit <= limit || upperLimit >= limit);
return limit;
}
Your do
/ while
condition describes the inverse of what you actually want to happen: you want the loop to end when limit
is between lowerLimit
and upperLimit
.
While you are at it, consider renaming the variable limit
to something more descriptive - say, value
, or result
, because the number the user entered is not used as a limit.
The condition should be
do {
...
} while(result < lowerLimit || result > upperLimit);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.