简体   繁体   中英

Program printing all 1's?

I want to have a number filled with 1's and 0's and convert it to boolean. However, when I run my code, it print's out all 1's. My code

I have almost all of the code finished, i know i'm just missing a piece possibly.

unsigned int booltoint(char number[], int length)
{
  int i;
  bool check;
  for(i = 0; i < length; i++)
{
    if(number[i] == 0)
    {
      check = false;
      printf("%d\n", check);
    }
    else
    {
      check = true;
      printf("%d\n", check);
    }
   }
  return check;
}


int main()
{
  int length;
  char number[] = "11001100";


  length = strlen(number);
  booltoint(number, length);

}

The issue is that you're comparing a char type with an int type.

While a char is technically an int, it's based in ASCII values . This means that, when you get the char at index i of char array number, you're returning the printable version of that char.

For example:
char '0' = int 48
char '1' = int 49
(You can see these values in the linked chart.)

Your check will always return false because no ASCII value is 0 (expect NULL, but that's another story).

The easiest (and most readable/maintable) way to correct the equality check is like this:

if (number[i] == '0')

or

if (number[i] == '1')

To see the ASCII representation of different numbers, you could run something like this:

int  i;

for (i=32; i<127; i++) {
    printf("%d: '%c'\n", i, i);
}

This is also a good time to learn about bit values as they relate to ASCII and control characters.

If you want to compact your code so it's easier to see what's really happening, look into the ternary operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM