I hope this example could help you:
Code:
/* Example for scanf to limit the number of characters where read into a string
In this example scanf reads only characters are stored between the square brackets
If the first character who is not in between the square brackets, input ends.
Example input is: 0101a
The result is 0101 (a not in list). decimal value is 5.
The numer 8 after the percent sign limits the number of characters to 8. */
#include <stdio.h>
#include <string.h> // strlen
// bintoint converts a binary(stored in a c-string) into a int-value,
// return value is the int-value
int bintoint(char binval[])
{
int i, lg, dumza = 0, testvalue = 1;
lg = strlen(binval);
testvalue <<= (lg - 1);
for (i = 0; i < lg; i++)
if ((binval[i] == 'I') || (binval[i] == '1')) dumza += testvalue >> i;
return dumza;
}
int main(int argc, char **argv)
{
char binval[20] = {0};
int decval = 0;
printf("Please input an 8 Bit binary value: ");
scanf("%8[01]", binval); // limit of characters where read is 0. Ends by the first character where is not 0 or 1
printf("input was: %s\n", binval);
decval = bintoint(binval);
printf("decimal value: %d\n", decval);
return 0;
}