Reputation: 3
I have a function to verify is the number is an integer, then I am trying to call this function to another that verifies if the number is on the limit. First it does not return the value and it returns to scan an integer, how do I fix that? and then it does matter the value I enter, 10 is always iVal. Why?
printf("Enter an integer between 10 and 20: ");
iVal = getIntLimited(10, 20);
printf("Your entered %d\n", iVal);
void flushKeyboard(void){
char enter;
do{
scanf("%c", &enter);
} while (enter != '\n');
}
int getInt(void){
int value;
char nl;
do{
scanf("%d%c", &value, &nl);
if (nl != '\n'){
flushKeyboard();
printf("Invalid integer, please try again: ");
return value;
}
} while (nl != '\n');
}
int getIntLimited(int lowerLimit, int upperLimit){
int iVal;
getInt() == iVal;
if ((getInt() > lowerLimit) && (getInt() < upperLimit)){
return iVal;
}
else{
printf("Invalid value, %d < value > %d: ", lowerLimit, upperLimit);
printf("\n");
}
}
Upvotes: 0
Views: 113
Reputation: 2668
Hope this way work for you
void flushKeyboard(void){
char enter;
do{
scanf("%c", &enter);
} while (enter != '\n');
}
int getInt(void){
int value;
scanf("%d", &value);
return value;
}
int getIntLimited(int lowerLimit, int upperLimit){
int iVal;
iVal = getInt();
printf(" %d \n", iVal);
if ( ( iVal > lowerLimit ) && ( iVal < upperLimit )){
printf("OK in bound\n");
return iVal;
}
else{
printf("Invalid value, %d < value > %d: ", lowerLimit, upperLimit);
printf("\n");
exit(0);
}
}
int main()
{
printf("Enter an integer between 10 and 20: ");
int iVal = getIntLimited(10, 20);
printf("Your entered %d\n", iVal);
}
Also you can use woz (above post) for getInt()
and code functionality doesn't change.
Upvotes: 0
Reputation: 574
As pointed by Vlad from Moscow, you need to assign the input to a variable and return it.
Your getInt()
function should be something like:
int getInt(){
int value;
char nl;
do{
scanf("%d%c", &value, &nl);
if (nl != '\n'){
flushKeyboard();
printf("Invalid integer, please try again: ");
}
}while (nl != '\n');
return value; //now you're returning the last scanned valid value!
}
Also, you're calling your getInt()
function three times:
1st) When you "enter" your getIntLimited()
function.
2nd) When you test getInt() > lowerLimit
3rd) When you test getInt() < upperLimit
Since the parameters lowerLimit
and upperLimit
are already passed to the function getIntLimited(int lowerLimit, int upperLimit)
, you don't need to get a value for them. So, I'd change your getIntLimited(int lowerLimit, int upperLimit)
function to:
int getIntLimited(int lowerLimit, int upperLimit){
int value;
value = getInt(); //assign the input value to a variable
if(value > lowerLimit && value < upperLimit){
return value; //now you're returning the value that you got on getInt()
}
else{
printf("Invalid value, %d < %d > %d: ", lowerLimit, value, upperLimit);
printf("\n");
}
return value; //now you're able to check for this value on the first printf: printf("Your entered %d\n", iVal);
}
Upvotes: 1