将 C + + 字符串分割为多行(代码语法,而不是解析)

不要与如何明智地分割字符串解析混淆,例如:
在 C + + 中拆分字符串?

对于如何在 c + + 中将字符串分割成多行,我有点困惑。

这听起来是一个简单的问题,但是举个例子:

#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;
}

我意识到我可以使用 std::string append()方法,但是我想知道是否有任何更短或更优雅的方法(例如更像 pythonlike,尽管显然 c + + 不支持三重引号等)来将 c + + 中的字符串分解成多行以便可读。

当您将长字符串字面值传递给函数(例如一个句子)时,这种方法尤其可取。

96007 次浏览

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.

#include <iostream>
#include <string>
main() {
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;
}

Note that if you want a newline in the literal, you will have to add that yourself:

#include <iostream>
#include <string>
main() {
std::string my_val ="This string gets displayed over\n"
"two lines when sent to cout.";
std::cout << "My Val is : " << my_val << std::endl;
}

If you are wanting to mix a #defined integer constant into the literal, you'll have to use some macros:

#include <iostream>
using namespace std;


#define TWO 2
#define XSTRINGIFY(s) #s
#define STRINGIFY(s) XSTRINGIFY(s)


int main(int argc, char* argv[])
{
std::cout << "abc"   // Outputs "abc2DEF"
STRINGIFY(TWO)
"DEF" << endl;
std::cout << "abc"   // Outputs "abcTWODEF"
XSTRINGIFY(TWO)
"DEF" << endl;
}

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 TWO to be made into a string literal.

Are they both literals? Separating two string literals with whitespace is the same as concatenation: "abc" "123" is the same as "abc123". This applies to straight C as well as C++.

I don't know if it is an extension in GCC or if it is standard, but it appears you can continue a string literal by ending the line with a backslash (just as most types of lines can be extended in this manor in C++, e.g. a macro spanning multiple lines).

#include <iostream>
#include <string>


int main ()
{
std::string str = "hello world\
this seems to work";


std::cout << str;
return 0;
}