为什么char []数组'\ 0'被std :: cin终止? [英] Why is a char[] array '\0' terminated by std::cin?

查看:56
本文介绍了为什么char []数组'\ 0'被std :: cin终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main() {
    char suffix[25];
    cout<<"Enter some suffix: ";
    cin >> suffix;
    cout << endl <<suffix;
}

请参见 完整示例

See the full sample

输入:

dog

输出:

dog

预期输出:

dog#*(!&!XΓ◘♪<♣@!(!)XΓ◘♪<♣☺XΓ◘♪<♣

关于指针(如果实际上确实与指针有关),我缺少的基本知识是什么?它们完全保留给出的内容的能力是什么?当我期望它是25时,甚至一个strlen(后缀)也会产生3.例如,打印后缀[6]根本不打印任何内容,甚至不打印空格

What is the fundamental thing I'm missing about pointers (if this does in fact have to do with pointers) and their ability to retain exactly what was given? Even a strlen(suffix) yields 3, when I expect it to be 25. Printing suffix[6], for example, prints nothing at all, not even a space

推荐答案

使用 cin cout 读写 char * 时,将其视为C样式的字符串. cin 在该行的末尾添加一个空终止符,而 cout 仅写入直到到达空终止符为止. strlen()对字符进行计数,直到终止符为空.

When you read or write a char* with cin and cout, it treats it as a C-style string. cin adds a null terminator at the end of the line, and cout only writes until it gets to the null terminator. strlen() counts characters until the null terminator.

后缀[6] 将包含分配数组时该字节中偶然发生的任何随机垃圾.如果您没有看到 cout<<后缀[6] ,这是因为随机垃圾恰好是非打印字符.

suffix[6] will contain whatever random garbage happened to be in that byte when the array was allocated. If you're not seeing anything with cout << suffix[6], it's because the random garbage happened to be a non-printing character.

这篇关于为什么char []数组'\ 0'被std :: cin终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆