Hi, guys.
I have problems understanding this program.
Code:
/*
By now you have probably experienced problems with scanf insofar as when an invalid character is typed things go drastically wrong. In “GETVAL.C” write and test two functions:
double get_double(void);
int get_int(void);
which loop, prompting the user, until a valid double/valid integer are entered.
*/
#include <stdio.h>
//FUNCTION PROTOTYPES
int get_int(void);
double get_double(void);
//MAIN FUNCTION
int main(void)
{
int i;
double d;
printf("type an integer ");
i = get_int();
printf("the integer was %i\n", i);
printf("type an double ");
d = get_double();
printf("the double was %lg\n", d);
return 0;
}
//FIRST FUNCTION
int get_int(void)
{
int result;
printf("> ");
while(scanf("%i", &result) != 1)
{
while(getchar() != '\n');
printf("> ");
}
return result;
}
//SECOND FUNCTION
double get_double(void)
{
double result;
printf("> ");
while(scanf("%lf", &result) != 1)
{
while(getchar() != '\n');
printf("> ");
}
return result;
}
I have problems understanding this loop in both subordinate made functions.
Code:
while(scanf("%lf", &result) != 1)
{
while(getchar() != '\n');
printf("> ");
}
Could you help me to understand? I've looked for additional information without success. I really don't get what's going there.
Thanks in advanced.