Question

I'm pretty sure the char type is for storing a single ASCII character unless any prefix is added. So with this in mind I use the std::string type included with <iostream> or <string> whenever I need it.

If I store "\n" inside a std::string and print it, it counts as a single character. Does this mean that I can fit the string in a char, even though it appears to consist of two characters?

Était-ce utile?

La solution

The newline character is a single (typically 8-bit) character. It's represented in program source (either in a character literal or in a string literal) by the two-character sequence \n.

So '\n' is a character constant representing a single character, the newline character.

On the other hand (as Paul Griffiths' answer points out), "\n" (with double quotes rather than single quotes) is a string literal that represents a string value. That string consists of two characters, a single '\n' newline character and a '\0' null character that marks the end of the string.

Autres conseils

The string "\n" is two characters, '\n' and '\0' - because C-style strings are terminated by a null character, implicit in this case - so no, you cannot fit it into a single char. You can obviously store an '\n' in a single char, but it will remain a single char, not a string.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top