-4

I want user to enter 2 digit binary number. The example below works fine unless I enter values such as "0" or "1". By the definition 0 and 1 is not a 2 digit binary but program treats 01 as 1 so it exits from while loop. How can I fix it ? Basically, how can i make computer to distinguish between 01 and 1?

int n_bin; 

while(n_bin!=01 && n_bin!=00 && n_bin!=10&&n_bin!=11) {;
    printf("Your entered number is %d\n Please enter a 2-digit binary number! \n",n_bin);
    scanf("%d",&n_bin);
}

I am allowed to use char, however I can't use an array.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Nagato
  • 87
  • 2
  • 8
  • I would think that `strtol(string, &endptr, 2)` would convert from the string to the binary number. – Iharob Al Asimi Mar 15 '17 at 13:31
  • 4
    If you're using an `int`, you can't distinguish. You would have to save to a `char` array (i.e., a string), and manipulate that to get what you want. – AntonH Mar 15 '17 at 13:33
  • handling by using a `switch` case would be better. – roottraveller Mar 15 '17 at 13:33
  • I am allowed to use char, however i cant use an array. But since char takes only the first element then for example 01 will be stored as just 48(ASCII of 0) – Nagato Mar 15 '17 at 13:36
  • You can't do it without an array! – Iharob Al Asimi Mar 15 '17 at 13:37
  • You can try saving the 2 characters into 2 different `char`s, but that's just making things complicated for yourself. Any reason why you can't use an array? – AntonH Mar 15 '17 at 13:42
  • school assignment. – Nagato Mar 15 '17 at 13:44
  • 1
    If you can't use arrays, you may have to use 2 `char`s not in an array (e.g.: `char c1, c2; scanf("%c%c", &c1, &c2);`). Because, again, with an int, it is not possible to distinguish between 1 and 01. – AntonH Mar 15 '17 at 13:48
  • `char buf[3]; .... scanf(" %2[01]", buf);` is a start. – chux - Reinstate Monica Mar 15 '17 at 13:50
  • @chux Even though I would say that your suggestion is the best, OP said no arrays because school assignment. – AntonH Mar 15 '17 at 13:50
  • @AntonH Important information like array restriction should be part of the post, not only in a comment. Post edited. – chux - Reinstate Monica Mar 15 '17 at 13:53
  • I would also like to point out that the conditions in the `while` loop are in decimal, not binary, so you're not going to get the desired behavior regardless. – AntonH Mar 15 '17 at 13:55
  • Read about encoding and representation of values in **binary** digital computers. And using decimal input to read a string of binary digits is a bad idea anyway. As others say, read a "string" and use `strtol` to convert to an integer (preferable `strtoul` to use an unsigned integer). If you are not allowed to use a `char []`, talk to your teacher, this restriction enforces bad code, something an assignment should **never** do. A good teacher will understand that and rethink his position. Feel free to cite me before your teacher. – too honest for this site Mar 15 '17 at 13:55

3 Answers3

2

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".

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • 1
    Don't forget to add check on `length`, it's not valid if it has a value other than 2. – AntonH Mar 15 '17 at 14:05
  • 1
    @AntonH OP has ambiguity in the length requirement: should it distinguish or only accept 2 digits? In any case, OP can add a length test of `if (length == 2)` or `if (length >= 1 && length <= 2)` as needed. – chux - Reinstate Monica Mar 15 '17 at 14:08
  • Even if length can be greater than 2, it should be restricted to being less than 32 to prevent `n_bin` from overflowing. – JeremyP Mar 15 '17 at 14:36
  • @JeremyP True about OF. Code could use additional code/length check or `unsigned` to handle overflow cases without UB or use `" %n%3d%n"` in the 2nd case. Many approaches. IMO, a robust solution would read a _line_ of user input into a _string_ and then parse it: something like a base 2 version of [#3 in this answer](http://stackoverflow.com/a/21666135/2410359). – chux - Reinstate Monica Mar 15 '17 at 14:53
  • Thanks. Gonna use this method. Highly appreciated. – Nagato Mar 15 '17 at 15:22
0

Why not have a loop that reads in 2 characters, making sure they're either a 0 or 1 and build up n_bin as you go along.

int i;
int n_bin=0;
int c;
int valid=0;
while(!valid)
  {
  valid=1;
  for(i=0;i<2;i++)
    {
    c=getchar();
    if ((c=='0')&&(c=='1'))
      {
      n_bin *= 2;
      n_bin += c-'0';
      }
    else
      {
      valid=0;
      break;
      }
    }
  if(!valid)
    {
    printf("Your entered number is %d\n Please enter a 2-digit binary number! \n",n_bin);
    }
  }
Chris Turner
  • 8,082
  • 1
  • 14
  • 18
0

there's no difference between 1 and 01 for the computer if the type is int. you can define two variable as below:

char digit1, digit2;
digit1 = getchar();
digit2 = getchar();
while( '0' <= digit1  && digit1 <= '9' && '0' <= digit2 && digit2 <= '9'){
//write the code you want.
//if diffrent instructions must be executed for 01 & 00, it must be written here.
//also instructions for other digits
}
Fatemeh Karimi
  • 914
  • 2
  • 16
  • 23