Is there any difference between '\n' and "\n

That's right), Is there any difference between '\n' and "\n.
'\n' - char literal
"\n" - string literal (array of 2 char)
Some lightning fast answer you got there),

Probably I asked the wrong question, which one is advised the first one or the second one?
When a single character is all that is needed, use '\n'
eg. std::cout << i << '\n' ;

When a null-terminated string is required, use "\n"
eg. std::strcat( cstr, "\n" ) ;
Thanks @JLBorges
When printing using std::cout or other std::ostreams ...

'\n' has the advantage that it's probably slightly more efficient (not that I think you would be able to notice).

"\n" has the advantage that it's much easier to add more characters later on without having to change the quotes.
Last edited on
Always nice to ready you answers @Peter)

other std::ostreams ..., I am thinking there is only std::cout and std::cerr that are ostreams, are there more?
Instances of std::ostringstream, std::ofstream, boost::asio::ip::tcp::iostream (third-party library) or your own class that inherits from std::ostream.

What I really meant was when you use << to output string literals.

In other situations there might be other trade-offs and you might not even have much of a choice (e.g. because a function only accepts a char or a string).
Last edited on
I am thinking there is only std::cout and std::cerr that are ostreams, are there more?


std::clog
https://en.cppreference.com/w/cpp/io/clog
https://en.cppreference.com/w/cpp/io/basic_ostream

Also there are the wcxxx versions (wcout, wcerr, wclog).
Understood, thank you everyone)
Registered users can post here. Sign in or register to post.