Not to be confused with how to split a string parsing wise, e.g.:
Split a string in C++?
I am a bit confused as to how to split a string onto multiple lines in c++.
This sounds like a simple question, but take the following example:
#include <iostream>
#include <string>
main() {
//Gives error
std::string my_val ="Hello world, this is an overly long string to have" +
" on just one line";
std::cout << "My Val is : " << my_val << std::endl;
//Gives error
std::string my_val ="Hello world, this is an overly long string to have" &
" on just one line";
std::cout << "My Val is : " << my_val << std::endl;
}
I realize that I could use the std::string append() method, but I was wondering if there was any shorter/more elegant (e.g. more pythonlike, though obviously triple quotes etc. aren’t supported in c++) way to break strings in c++ onto multiple lines for sake of readability.
One place where this would be particularly desirable is when you’re passing long string literals to a function (for example a sentence).
Don’t put anything between the strings. Part of the C++ lexing stage is to combine adjacent string literals (even over newlines and comments) into a single literal.
Note that if you want a newline in the literal, you will have to add that yourself:
If you are wanting to mix a
#defined integer constant into the literal, you’ll have to use some macros:There’s some weirdness in there due to the way the stringify processor operator works, so you need two levels of macro to get the actual value of
TWOto be made into a string literal.