View Full Version : "clearing buffer" perplexed

01-04-2015, 11:25 AM
I'm lost with my novice attempts to clear the terminal '\n' generated in the following code, so that it willwork properly, and hope someone can steer me in the right direction.

/* convert bitval to decimal */
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
int bstr_to_dec(const char * str);
bool check_val(const char * str);
int main(void)
char value[8 * sizeof (int) + 1];
printf("Enter a binary number with up to %d digits, or"
"'q' to terminate: ", 8 * sizeof(int));
while (fgets(value,33,stdin) != NULL && value[0] != '\0'
&& toupper(value[0]) != 'Q')
if (!check_val(value))
puts("A binary number contains just 0s and 1s.");
printf("%s is %d\n", value, bstr_to_dec(value));
puts("Enter next value:");
return 0;

int bstr_to_dec(const char * str)
// calculate decimal value
int val = 0;
while (*str != '\0')
val = 2 * val + (*str++ - '0');
return val;

bool check_val(const char * str)
// check for proper binary input values
bool valid = true;

while (valid && *str != '\0')
if (*str != '0' && *str != '1')
valid = false;
return valid;

01-04-2015, 04:53 PM
Damn, code boxes don't format well for mobile, so I'm having trouble seeing your end code or seeing what its actually doing, so what's the output if you can give an example.

Can't say what you are having problems with but notice that you should be using unsigned long into %lu instead of %d for your calculation but that would only be warning so not your problem.

When I get access to a computer and compiler to see your code in action it should be obvious but I can't see it all.



01-04-2015, 07:14 PM
Hmm. Where's our local friendly webdevguy (http://pressf1.pcworld.co.nz/member.php?40209-Webdevguy)?

02-04-2015, 12:47 PM
Well I can read all your code now I'm on a laptop.

I think you are a bit confused about "clearing buffer". What you are experiencing is how fgets() is implemented, it actually keeps the line feed character and puts a null character on the end. So you're stuck with a continuous check value that keeps failing due to it reading the line feed character.

gets() does not have that issue but has other serious security issues which is why it shouldn't be used.

You could implement an rtrim()/rstrip() function to remove the characters off the end of the string including NULL and just put NULL on the end yourself.

If that's not the issue you are experiencing, you really need to explain more about what it is that isn't working, I'm just doing a lot of guessing at this stage.