I have a problem with flushing the buffer, I don't wanna use fflush( stdin ) for many said that it's providing abnormal behavior. I have the program below, if I exceeded the size of the buffer I am not able to enter any input for the salary. thanks.

if you are sure that salary line is not more than 5 digits (including decimal point) always

you think too low about salaries?

03-03-2009

cpjust

I wish my salary was more than 5 digits.

03-03-2009

Meldreth

you can flush the buffer with a loop. input is line oriented and you can be pretty sure that users have to type enter at the end, so you can just search for that character.

Code:

while (getchar() != '\n') ;

sometimes that doesn't work as well as you want, like if you don't know if there's anything in the buffer but you want to flush it if there is. if there's nothing in the buffer that loop will wait for input before finishing instead of not running at all. i don't think there's a portable way to find out of there's anything in the buffer without waiting, but you can do it if you know how stdin works on the inside.

this works on microsoft compilers. if it's a microsoft compiler then _MSC_VER will be defined and flush fixes the buffer's insides to do what i want. if _MSC_VER isn't defined, the portable loop strategy is used instead. you can add #elif's for other compilers too.

Quote:

Originally Posted by vart

simplest way - do not use scanf - use fgets+sscanf and you do not need flushing at all

it's not that simple. if the input is longer than the size passed to fgets, the rest of the input stays in the stream buffer. unless you want to write a function that grows a string dynamically to take the whole line, you still have to do something with the leftovers or the rest of the input will get corrupted.

03-04-2009

$l4xklynx

about the salary, I understand what you mean but the program is just for testing. I coded a function showed below.