简体   繁体   English

为什么char []数组'\\ 0'被std :: cin终止?

[英]Why is a char[] array '\0' terminated by std::cin?

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

See the full sample 查看完整样本

input: 输入:

dog

output: 输出:

dog

expected output: 预期输出:

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

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 甚至一个strlen的(后缀)产生3,当我希望它是25打印后缀[6]中,例如,在所有的打印无关,甚至没有空间

When you read or write a char* with cin and cout , it treats it as a C-style string. 当您使用cincout读写char*时,会将其视为C风格的字符串。 cin adds a null terminator at the end of the line, and cout only writes until it gets to the null terminator. cin在该行的末尾添加了一个空终止符,而cout只写直到到达空终止符为止。 strlen() counts characters until the null terminator. strlen()计算字符,直到终止符为空。

suffix[6] will contain whatever random garbage happened to be in that byte when the array was allocated. suffix[6]将包含分配数组时该字节中发生的任何随机垃圾。 If you're not seeing anything with cout << suffix[6] , it's because the random garbage happened to be a non-printing character. 如果您没有看到cout << suffix[6]任何内容,那是因为随机垃圾恰好是一个非打印字符。

The << operator with a char* right operand reads from the stream and writes a C-style string to the specified array. 带有char*右操作数的<<运算符从流中读取并将C样式的字符串写入指定的数组。 (The char* value is the result of the implicit conversion of the array expression suffix .) char*值是数组表达式suffix的隐式转换的结果。)

It stores a terminating null character '\\0' into the array to mark the end of the string. 它将终止的空字符'\\0'到数组中以标记字符串的结尾。 The contents of the array after the '\\0' are left alone. '\\0'之后的数组内容将保留。

strlen and cout << suffix both look for this terminator to determine how long the string is. strlencout << suffix都将查找此终止符,以确定字符串的长度。

As for suffix[6] , that's a valid element of the array, but it's beyond the end of the string. 至于suffix[6] ,它是数组的有效元素,但超出了字符串的末尾。 Its contents are garbage. 它的内容是垃圾。 It's fairly likely, though by no means certain, that it contains a null character; 尽管没有确定,但很有可能包含一个空字符。 printing it will probably have no visible effect. 打印它可能没有可见的效果。 If you convert it to an int , you can see the actual value. 如果将其转换为int ,则可以看到实际值。

cin installs a null after "dog"; cin在“ dog”之后安装了null; as a result cout stops showing characters after "dog". 结果, cout停止在“ dog”之后显示字符。 This is by c++ method for recognizing end of character strings. 这是通过c ++方法识别字符串结尾的。

Nothing pointer-ish here 这里没有指针

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM