Cout c++ in many lines
14,210
Solution 1
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.
Solution 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.
Author by
LearnToGrow
Updated on July 21, 2022Comments
-
LearnToGrow almost 2 years
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?
-
M.M about 10 yearsOriginal version should also work (maybe with some excess whitespace)
-
Emmet about 10 yearsThat'd be a pretty long error message. Might want a newline in there somewhere.
-
Mats Petersson about 10 years@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...
-
Retired Ninja about 10 yearsYou 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.
-
Mats Petersson about 10 years@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).
-
Retired Ninja about 10 years@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.
-
M.M about 10 yearsMy 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.