PDA

View Full Version : fflush didn't work



juandy
11-23-2001, 06:38 AM
I try to validate the kode inputs by using getche to validate each characters input,after that i ask the name {gets(nama);} instead of receiving input the program passes it.
my codes:


char kode[4];
char nama[20];
void menu()

{
char input;
int i=0;
printf("\n");
gotoxy(1,7);
printf("KODE : ");
do
{ gotoxy(12+i,7); printf(" ");
gotoxy(12+i,7);
input=getche();
if(input==8&&i>0)
i--;
else
if(i<=2&&((input>=48&&input<=57)||(input>=97&&input<=122))) /*validasi per karakter*/
{ kode[i]=input;
i++;
}
} while(input!=13||i!=3);
gotoxy(1,8);
printf("NAMA : ");
do{gotoxy(12,8);clreol();
gotoxy(12,8);fflush(stdin);gets(nama);
}while(strlen(nama)>20);
}

Salem
11-23-2001, 09:47 AM
First the trivial errors
> if(input==8&&i>0)
Try writing this as
if ( input == '\b' && i > 0 )

> if(i<=2&&((input>=48&&input<=57)||(input>=97&&input<=122)))
Ditto
if ( i <= 2 && ((input>='0' &&input<='9' )||(input>='a' &&input<='z' )))

Both improve readability and portability

> while(input!=13||i!=3);
Since you seem to be using DOS specific input routines, I guess this should be
while ( input != '\r; || i!=3 );

> fflush(stdin);
Flushing input streams is an undefined operation - so you need to use something else.

Like this perhaps
while ( getchar() != '\n' ) continue;

Or perhaps (since this is non-ANSI)
while ( getch() != '\r' ) continue;

> gets(nama);
> }while(strlen(nama)>20);
Now here's the real problem - if strlen(nama) is > 20, you've already trashed memory you don't own (and you might not even get a chance to strlen it). Even if you do, your program is already wrong.
Use fgets to read input - at least it will not exceed the limits of the buffer you supply.

Generator
11-23-2001, 02:31 PM
How long have you been programming salem, you know everything. Have you written any tuts?