7

This is my test code

#include<iostream>
using namespace std;
int main() 
{
    uint8_t a;
    while(1)
    {
        cin>>a;
        if(a == 0) break;
        cout<<"Input is "<<a<<endl;
    }
}  

When I execute (with my inputs), this is what I get

1
Input is 1
2
Input is 2
12
Input is 1
Input is 2
0
Input is 0
3  
Input is 3

Problem1: It takes input 12 as two separate inputs

Problem2: Condition if a==0 doesn't work

What might be the problems?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Nick
  • 949
  • 1
  • 11
  • 31

2 Answers2

9

uint8_t is a typedef for an unsigned char. This means that one character will be read from cin.

When "0" is read it is actually the ascii value of the character '0' commonly 48, which is not zero hence the equality check fails.

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • Thanks for the info. I want to know if we have any datatype to store small numbers. – Nick Jul 03 '12 at 10:29
  • @neeradkumar, you can use `uint8_t` to store small numbers but not to read it using `cin`. – hmjd Jul 03 '12 at 10:33
  • 1
    I want to read numbers from cin in my code. I guess I can take input to a int and then equal it to a uint8_t ? – Nick Jul 03 '12 at 10:35
  • 1
    yes, but check the that value of the read `uint16_t` or `int` can fit in a `uint8_t` before assigning. – hmjd Jul 03 '12 at 10:36
  • is there any easy way to typecast int to uint8_t? – Nick Jul 03 '12 at 10:48
  • 2
    `uint8_t v = static_cast(i);` where the value of `i` is a valid value (0 - 255) for a `uint8_t`. – hmjd Jul 03 '12 at 10:52
4

uint8_t is the same as a char, so trying to extract one from cin probably just gives you the next character to be typed.

The values to receive are then not character-translated-to-int, but the ascii values of the inputs. When you type 0 you're getting ascii \0 rather than int zero, so your test for zero isn't triggered. Try if( a == '0') to see what I mean.

RobH
  • 3,199
  • 1
  • 22
  • 27