Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "\n" considered one or two characters, and can it be stored in a char?

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?

like image 872
Magnusbon Avatar asked Apr 27 '14 03:04

Magnusbon


2 Answers

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.

like image 166
Keith Thompson Avatar answered Oct 18 '22 05:10

Keith Thompson


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.

like image 21
Crowman Avatar answered Oct 18 '22 03:10

Crowman