-
do{}while loop trouble
Where did I go wrong with this code for my do while loop?
Code:
int main()
{
char response;
do
{
/* My main code would be here */
printf("\n\n\nDo you wish to convert another number? (y) or (n): ");
scanf("%c", &response);
while(!(response == 'y' || response == 'Y' || response == 'n' || response == 'N'))
{
printf("\nPlease enter (y) or (n): ");
scanf("%c", &response);
}
} while(response == 'y' || response == 'Y');
return 0;
}
The output when the program goes to the do while loop is:
Code:
Do you wish to convert another number? (y) or (n):
Please enter (y) or (n):
For some reason that I do not see the program skips the first scanf() and enters the while loop going instead to the second scanf(). What am I doing wrong?
Also does C have and equal to the C++ ignore function? I would normally code the response input as:
Code:
cin >> response;
cin.ignore(100, '\n');
I do not know if C has something similar to this for garbage clean-up.
-
No, it doesn't have a cleanup method. You can do one of a few things:
1) Use fgets, read into a buffer, and get it from there.
2) Use something like:
Code:
void clean( void )
{
int c;
while( (c=fgetc()) != '\n' && c != EOF )
;
}
3)You can modify parameters to scanf to ignore the newline.
Code:
scanf("%c*[^\n]*%c", &response );
There are a few others, but those should do.
Quzah.
-
Quote:
Originally posted by quzah
3)You can modify parameters to scanf to ignore the newline.
Code:
scanf("%c*[^\n]*%c", &response );
cool!! Is there a place where I can learn more about these parameters? (i.e. on the web/any book ?)
-
quzah
I really like the C++ ignore...oh well. As for the parameter combo:
Code:
scanf("%c*[^\n]*%c", &response );
I never would have thought that one up, thanks.