无符号字符的标准输入 [英] Standard Input for Unsigned Character
问题描述
我试图通过程序发送无符号字符,我想能够通过标准输入(即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。
因为 另一方面,在 您可能想要这样: 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: I get 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 On the other hand, in You probably want this:
这篇关于无符号字符的标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 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;
}
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;
}
Enter values: 2
d=2
e=☻
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.unsigned char e = 2;
you explicitly assign a value (2
) to the variable, so the compiler blindly assigns it to 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;
}