13
I’m having trouble with the job scanf();
. When reading two or more values, the later values are not read.
I’ve already tried:
__fpurge(stdin);
After reading, but in this case I need to enter after each reading, which is a little uncomfortable for me.
I’ve also tried:
fflush(stdin);
But it doesn’t (I’m using Debian 7.1, I think fflush(stdin);
only work on Windows)
What solved my problem was:
#include <stdio.h>
//Limpa o buffer do teclado
void flush_in(){
int ch;
while( (ch = fgetc(stdin)) != EOF && ch != '\n' ){}
}
int main(){
char c;
printf("\nEntre com um caractere: ");
scanf("%c",&c);
flush_in();
printf("\nO caractere: \"%c\" tem o valor ASCII %d", c ,(int)c);
printf("\nEntre com um caractere: ");
scanf("%c",&c);
flush_in();
//__fpurge ( stdin );
printf("\nO caractere: \"%c\" tem o valor ASCII %d", c ,(int)c);
printf("\nPress any key to exit...\n\n");
getchar();
return 0;
}
But the function code flush_in()
, that I got here, is obscure to me.
So...
- Why this problem occurs?
- How to solve this problem so that the same code works in Windows and Linux environments after being compiled?
What does the code snippet below?
void flush_in(){ int ch; while( (ch = fgetc(stdin)) != EOF && ch != '\n' ){} }
Please excuse the formatting. I could not format the last code snippet. I also could not put "flush_in();" in bold and italic. If anyone sees, please edit.
– Avelino
Because when a single character is read the terminator (generated by ENTER) continues in the buffer. The function discards this character. Note that there are other ways to discard this "dirt" of the input buffer, for example infoemndo in the next reading that should disregard an eventual ' n' present in the input buffer.
– user4552
I fixed the formatting of that last block. To format code blocks within list items, you need to double indent.
– bfavaretto
Thank you/ I was unable to place. The title and tags improved a lot too.
– Avelino