简体   繁体   中英

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

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.

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.

The << operator with a char* right operand reads from the stream and writes a C-style string to the specified array. (The char* value is the result of the implicit conversion of the array expression suffix .)

It stores a terminating null character '\\0' into the array to mark the end of the string. The contents of the array after the '\\0' are left alone.

strlen and cout << suffix both look for this terminator to determine how long the string is.

As for suffix[6] , that's a valid element of the array, but it's beyond the end of the string. 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.

cin installs a null after "dog"; as a result cout stops showing characters after "dog". This is by c++ method for recognizing end of character strings.

Nothing pointer-ish here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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