Unexpected results when printing array and char to screen with cout(使用 cout 将数组和字符打印到屏幕时出现意外结果)
问题描述
作为一个学习 C++ 的初学者,我试图理解 char 类型的数组和 int 类型的数组之间的区别.这是我的代码:
As a beginner of learning C++, I am trying to understand the difference between an array of type char and an array of type int. Here is my code:
void IntArray () {
int array[5] = {5,6,7,8,9};
cout << "Print int array: " << array << endl;
cout << "Print int array[0]: " << array[0] << endl;
cout << "Print int array[0]+1: " << array[0]+1 << endl;
}
void CharArray () {
char array[5] = {'a', 'b', 'c', 'd', ' '};
cout << "Print char array: " << array << endl;
cout << "Print char array[0]: " << array[0] << endl;
cout << "Print char array[0]+1: " << array[0]+1 << endl;
}
这是输出:
Print int array: 0xbfd66a88
Print int array[0]: 5
Print int array[0]+1: 6
Print char array: abcd
Print char array[0]: a
Print char array[0]+1: 98
我的问题是:
为什么下面会输出字符串'0xbfd66a88'?我期待它返回数组中第一个元素的地址:
Why does the following output the string '0xbfd66a88'? I was expecting it to return the address of the first element in the array:
cout << "Print char array: " << array << endl;
为什么下面的输出是'98'?我期待它输出字母'b':
Why does the following output '98'? I was expecting it to output the letter 'b':
cout << "Print char array[0]+1: " << array[0]+1 << endl;
推荐答案
1.
因为当您将 char 数组流式传输到 cout 时,它们的处理方式与其他数组不同 - << 运算符为 <代码>const char*.这是为了与 C 兼容,因此以 null 结尾的 char 数组被视为字符串.
1.
Because char arrays are treated differently to other arrays when you stream them to cout - the << operator is overloaded for const char*. This is for compatibility with C, so that null-terminated char arrays are treated as strings.
请参阅这个问题.
这是由于整体推广.当您使用 char(值为 'a')和 int(值为 1)调用二进制 + 时,编译器会提升您的char 为 signed int 或 unsigned int.哪一个是特定于实现的——它取决于默认情况下 char 是有符号还是无符号,以及哪个 int 可以采用 char 的全部范围.因此,+ 操作符被调用时使用值 '97' 和 '1',它返回值 '98'.要将其打印为 char,您需要先转换它:
This is due to integral promotion. When you call the binary + with a char (with value 'a') and an int (with value 1), the compiler promotes your char to either a signed int or an unsigned int. Which one is implementation specific - it depends on whether char is signed or unsigned by default, and which int can take the full range of char. So, the + operator is called with the values '97' and '1', and it returns the value '98'. To print that as a char, you need to first cast it:
cout << "Print char array[0]+1: " << static_cast<char>(array[0]+1) << endl;
请参阅这个问题.
这篇关于使用 cout 将数组和字符打印到屏幕时出现意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 cout 将数组和字符打印到屏幕时出现意外结果
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
