cout返回两次字符字符串
以下代码的输出是
Toto
TotoToto
但我希望只是
Toto
Toto
为什么第二个 cout 重复输出中的字符串?
我在 Ubuntu 上使用 g++ 7.5.0 版,我不确定这是否相关。
代码如下:
#include<iostream>
using namespace std;
int main(){
char c1[] = "Toto";
char c2[4] = {'T','o','t','o'};
cout << c1 << endl;
cout << c2 << endl;
return 0;
}
回答
当您输出一个字符数组时,它必须 - 按照约定 - 以 null 结尾,否则您有未定义的行为。
更改c2如下,它将按预期开始工作:
char c2[5] = {'T','o','t','o', ' '};
在 的情况下c1,它假设您需要附加隐式空值并c1自动设置大小以允许空间,因此如果您使用sizeof或std::extent<>获取 的大小,c1您将看到它是 5 个字节。
Drew 的评论建议解释在调用函数时数组衰减到指针,所以这里是。当你写:
cout << c2;
编译器调用函数std::ostream& operator<<(std::ostream&, const char*)。数组c2 衰减为 a char*,允许匹配和调用函数,但这样做会丢失所有关于文本长度的知识。函数实现要求您遵循在要流式传输的文本之后使用空终止符的约定。如果你想明确控制应该打印多少个字符,你可以使用例如std::cout.write(c2, 3). std::strings 的工作也更直观——初学者应该更喜欢使用std::strings 来存储和操作文本。
- @user106306 Probably, your compiler placed `c2` just before `c1` on the stack which leads to your stack looking like `TotoToto ` starting with `c2[0]`. It makes it looks like `&c2[0]` points to a null terminated character string that contains 8 characters before the null terminator. Edit : Since this is Undefined Behavior, the output of your program can change at any time for no apparent reason. You can't rely on this layout always being true.