gpt4 book ai didi

c++ - C 字符串比定义的长度短一个字符?

转载 作者:太空狗 更新时间:2023-10-29 20:12:15 24 4
gpt4 key购买 nike

对 c++ 很陌生,我有以下代码:

char input[3];

cout << "Enter input: ";
cin.getline(input,sizeof(input));
cout << input;

输入类似abc 的内容只会输出ab,将其缩短一个字符。定义的长度是3个字符,为什么只捕获2个字符?

最佳答案

请记住,C 字符串以 null 结尾。由于空终止符,要存储 3 个字符,您需要为 4 个字符分配空间。

另外正如 @MikeSeymour 在 c++ 的评论中提到的,最好完全避免这个问题并使用 std::string。

关于c++ - C 字符串比定义的长度短一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28703270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com