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

Sep 18, 2022 at 4:22am
That's right), Is there any difference between '\n' and "\n.
Sep 18, 2022 at 4:25am
'\n' - char literal
"\n" - string literal (array of 2 char)
Sep 18, 2022 at 4:33am
Some lightning fast answer you got there),

Probably I asked the wrong question, which one is advised the first one or the second one?
Sep 18, 2022 at 5:01am
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" ) ;
Sep 18, 2022 at 5:17am
Thanks @JLBorges
Sep 18, 2022 at 7:31am
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 Sep 18, 2022 at 7:43am
Sep 18, 2022 at 8:17am
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?
Sep 18, 2022 at 8:42am
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 Sep 18, 2022 at 9:10am
Sep 18, 2022 at 9:02am
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).
Sep 18, 2022 at 9:55pm
Understood, thank you everyone)
Topic archived. No new replies allowed.