无符号字符的标准输入 [英] Standard Input for Unsigned Character

查看:319
本文介绍了无符号字符的标准输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过程序发送无符号字符,我想能够通过标准输入(即std :: cin)获取数字。例如,当我输入2我想它发送☻(unsigned char 2)。当我使用代码:

  std :: cout< 输入值:; 
{
unsigned char d;
unsigned char e = 2;
std :: cin>> d;
WriteFile(file,& d,1,& written,NULL);
std :: cout<< d =<< d<< \\\
;
std :: cout<< e =< e;
}

我得到

 输入值:2 
d = 2
e =☻

任何人都可以告诉我为什么d被解释不正确为unsigned char 50而e被正确解释为unsigned char 2?



当然,在您解释之后,您可以解释如何获取用户输入并将其转换,以便我发送2而不是2。

解决方案

因为 std :: cin>> d; 默认读取 char 类型,因此输入 2 2 (ASCII代码为50),而不是由ASCII代码2表示的字符。这是正常的行为,否则尝试从 cin c>

另一方面,在 unsigned char e = 2; 你显式地为变量赋值( 2 ),所以编译器盲目地赋值给 e



您可能想要这样:

  #include< iostream> ; 
#include< string>
using namespace std;

int main(int argc,char * argv [])
{
string myString;
cin>> myString;
char c = atoi(myString.c_str());
cout<< c<< endl;
}


I am trying to send unsigned characters through a program, and I would like to be able to get the numbers through standard input (ie std::cin). For example when I type 2 I would like it send ☻ (unsigned char 2). when I use the code:

 std::cout << "Enter values: ";
            {
                unsigned char d;
                unsigned char e = 2;
                std::cin >> d;
                WriteFile(file, &d, 1, &written, NULL);
                std::cout << "d= " << d << "\n"; 
                std::cout << "e= " << e;
            }

I get

 Enter values: 2
 d=2
 e=☻

Can anyone tell me why d is being interpreted Incorrectly as unsigned char 50 while e is being interpreted correctly as unsigned char 2?

And of course after your explanation can You explain how to get User input and convert it so that I send 2 rather than '2'.

解决方案

Because std::cin >> d; reads by default a char type, so the input 2 translates into the character 2 (with ASCII code 50) and not the character represented by the ASCII code 2. This is a normal behaviour, otherwise trying to read numbers from cin will end up being a mess.

On the other hand, in unsigned char e = 2; you explicitly assign a value (2) to the variable, so the compiler blindly assigns it to e.

You probably want this:

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char *argv[])
{
    string myString;
    cin >> myString;
    char c = atoi(myString.c_str());
    cout << c << endl;
}

这篇关于无符号字符的标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆