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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With