[英]printf integer displays more than C++ cout
I'm a C programmer picking up C++我是一名 C 程序员,正在学习 C++
Seems cout is a bit clunky, I don't understand why it produces a different output.似乎 cout 有点笨重,我不明白为什么它会产生不同的输出。
//The printf below displays value 50
//The cout below display value 2
data_to_send.data[2] = atoi(data_str.c_str());
printf("\n DEBUG: %d\n",data_to_send.data[2]);
std::cout << "Debug: " << std::dec << data_to_send.data[2];
Your data_to_send.data[2]
field is a char
or unsigned char type
(byte).您的data_to_send.data[2]
字段是char
或unsigned char type
(字节)。
printf
sees it as the integer 50
, as requested by the format specifier %d
.根据格式说明符%d
要求, printf
将其视为整数50
。
cout
sees it as the character '2'
, of ASCII code 50
, as implictly requested by the data type. cout
将其视为 ASCII 代码50
的字符'2'
,这是数据类型隐式请求的。
My guess is that data_to_send.data
is char*
, so data_to_send.data[2]
is char with value 50
.我的猜测是data_to_send.data
是char*
,所以data_to_send.data[2]
是值为50
char 。 When you call printf
you specify to treat your argument as integer ( %d
) so it prints 50
.当您调用printf
您指定将参数视为整数( %d
),因此它打印50
。 In C++ cout
uses function overloading to call concrete function to concrete type of argument, in this case operator<<
for char
.在 C++ 中, cout
使用函数重载来调用具体函数到具体类型的参数,在这种情况下operator<<
for char
。 ASCII value of '2'
is 50
, thats why 2
is printed out. '2'
ASCII 值是50
,这就是打印出2
原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.