No analysis of int n_bin
will determine if it was assigned with user input of "1"
or "01"
. Code needs to looks at the point of user input to distinguish.
Reading in using characters:
Read user input, one character at a time. Look for '0'
, '1'
, '\n'
, EOF
or something else.
int n_bin = 0;
int length = 0;
int ch;
while ((ch = fgetc(stdin)) >= '0' || ch <= '1') {
n_bin = n_bin*2 + (ch - '0'); // *2 as this is base 2
length++;
}
if (ch = '\n' || ch == EOF) {
printf("Value (in decimal):%d Character length:%d\n", n_bin, length);
if (n_bin < 0 || n_bin > 3 || length != 2) puts("Non-conformance"):
} else {
puts("Unexpected character entered");
}
Reading in as int
, noting character offsets:
Should you care for a more advanced approach, use "%n"
which record the number of characters scanned.
int n_bin;
int start, end;
// v------- Consume leading white-space
// | v----- Store # of characters read
// | | v--- Scan/store int
// | | | v- Store # of characters read
int retval = scanf(" %n%d%n", &start, &n_bin, &end);
if (retval == 1) {
if ((end - start) == 2 && n_bin >= 0 && n_bin <= 3) {
puts("Success");
} else {
puts("Fail");
}
else {
// consume remaining characters in line
http://stackoverflow.com/q/34219549/2410359
puts("Fail");
}
Note: This second approach will pass input like "+1"
.