Cout c++ in many lines
Asked Answered
D

2

5

I want to print a large message in c++ using cout.

example:

cout<<"Camera could not be opened in the requested access mode, because another
              application (possibly on another host) is using the camera."<<endl;

but I get an error.

any help?

Diplomat answered 4/4, 2014 at 22:52 Comment(2)
.. and what is the error?Argus
If it's an error message, it should arguably be sent to cerr rather than cout.Thespian
F
14

Something like this:

 cout<<"Camera could not be opened in the requested access mode, because another "
          "application (possibly on another host) is using the camera."<<endl;

or

 cout<<"Camera could not be opened in the requested access mode, because another\n"
          "application (possibly on another host) is using the camera."<<endl;

In C and C++, two strings next to each other will be concatenated by the compiler.

Flotilla answered 4/4, 2014 at 22:55 Comment(7)
Original version should also work (maybe with some excess whitespace)Shrewd
That'd be a pretty long error message. Might want a newline in there somewhere.Thespian
@MattMcNabb: Really? Both g++ and clang++ objects when I have a newline in the middle of a string. Not sure which compiler you are using...Flotilla
You need a \ at the end to make it work, just like a multiline macro if you don't use extra quotes. The extra quotes are generally more readable and preferable imo.Dionysiac
@RetiredNinja: That would also work, but that's just hard to read and error prone. I often use " ... " "...." over multiple lines for long text messages, and it typically formats nicely on the screen that way too. Don't think I've ever used backslash in such a case. What's the benefit (aside from saving one character, but diskspace is relatively cheap these days).Flotilla
@MatsPetersson I totally agree. You can make it work without quotes, but it just looks wrong to me. It also tends to break syntax highlighters.Dionysiac
My bad, I was thinking of a version with the backslash. C++11 allows "raw" string literals without it but this isn't one of those either.Shrewd
I
2

You can't split normal string literals across multiple lines directly. I think you can split them across lines using the concatenation character. However, that also wouldn't embed newlines. To get these you'd need to use \n. I think you can use raw stringliterals though:

char const* strcont = "foo\
bar";
char const* strcat = "foo"
                     "bar";
char const* strraw = R"(foo
bar)";

The first two strings are the same: adjacent strings are concatenated. The third one also contains a newline.

Idiolect answered 4/4, 2014 at 23:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.