-
do..while loop problems
I don't know if this is OS-related or not. I'm compiling with DJGPP on a machine that is running WinME. Here is the code:
Code:
do {
gotoxy(24,7);
cscanf(" %u",&type);
fflush(stdin);
if (type <= 0 || type >= 8)
{
gotoxy(24,7);
clreol();
gotoxy(23,9);
textcolor(RED);
cprintf("ERROR! Please enter from menu");
}
else
return type;
}
while (type != 0);
Now whenever I run this loop.. it won't allow me to re-input the value that is stored at type. The value is a single digit. It just keeps going through the loop until I break and exit the program manually.
Also if i change the while condition to while (type == 0); it doesn't go through the loop and continues on with the problem. Any help is grateful. I've been pulling my hair out last night trying to fix it, but to no avail.
-
you've got a type conflict... returning an address is fine, but if you've got 'type' an integral type, then you're passing cscanf the wrong argument... if it's a string type, you've got a conditional with strings...
-
Sorry, just gotta laugh
> fflush(stdin);
When I tirelessly tell people that this might work on their compiler, but it wont work on mine, I'm not just saying it, I really mean it.
Congratulations, you've started using the same compiler as me, and now you've discovered the brutal reality of the situation - flushing stdin is undefined.
If you want to flush stdin, then do this
Code:
while ( getchar() != '\n' ) continue;
It should also check for EOF, but that's an exercise for the reader :)
The space before the %u is seldom ever necessary
-
do..while loop problem
Dear catalyst
I do not think the problem is OS related. It is more likely to do with your use of "return". RETURN is defined as "Exits immediately from the currently executing function to the calling routine, optionally returning a value.". I appreciate that you have not reproduced the whole code. Please consider removing the else and its content.
"else
return type"
With these removed, if a user enters a number within the required range, 1 - 7 inclusive then no else is needed, it will loop. If a user enters a number outside the range but not zero the error message is printed. Please also note that after the error message prints to screen and the user enters a number within the range 1 -7 inclusive the error message still remains on the screen, giving the impression that the correct input was incorrect. I have not attempted to fix this problem with the error message in the code below, only the loop problem.
#include<stdio.h>
void main()
{
int unsigned type;
do
{
gotoxy(24,7);
cscanf(" %u",&type);
fflush(stdin);
if (type <= 0 || type >= 8)
{
gotoxy(24,7);
clreol();
gotoxy(23,9);
textcolor(RED);
cprintf("ERROR! Please enter from menu");
}/*End of if*/
}while (type != 0);
}/*End of main()*/