uint8_t does not take two digit inputs

安稳与你 提交于 2019-12-04 23:47:33

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11308898/uint8-t-does-not-take-two-digit-inputs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!