将C++字符串拆分为多行(代码语法,非解析)

Jas*_*ick 66 c++ string syntax coding-style readability

不要混淆如何拆分字符串解析明智,例如:
在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;
}
Run Code Online (Sandbox Code Playgroud)

我意识到我可以使用这个std::string append()方法,但我想知道是否有任何更短/更优雅(例如更多pythonlike,但显然三重引号等在c ++中不支持)的方式将c ++中的字符串分解为多行为了缘故可读性.

特别需要的地方是将长字符串文字传递给函数(例如句子).

Ecl*_*pse 106

不要在琴弦之间放任何东西.C++ lexing阶段的一部分是将相邻的字符串文字(甚至是换行符和注释)组合成一个文字.

#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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果您想在文字中添加换行符,则必须自己添加:

#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;
}
Run Code Online (Sandbox Code Playgroud)

如果你想将一个#define整数常量混合到文字中,你将不得不使用一些宏:

#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;
}
Run Code Online (Sandbox Code Playgroud)

由于stringify处理器操作符的工作方式,因此存在一些奇怪之处,因此您需要两个级别的宏来获取TWO字符串文字的实际值.

  • 组合字符串文字是词汇阶段(不是预处理器)的实际部分,因为像这样的字符串拆分被定义为语言的一部分. (4认同)

mkb*_*mkb 9

他们都是文字吗?用空格分隔两个字符串文字与连接相同:"abc" "123"与...相同"abc123".这适用于直C和C++.


rme*_*dor 7

我不知道它是 GCC 中的扩展还是标准的,但看起来你可以通过用反斜杠结束行来继续字符串文字(就像大多数类型的行可以在 C++ 中的这个庄园中扩展一样,例如跨越多行的宏)。

#include <iostream>
#include <string>

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

    std::cout << str;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 该字面语法在“world”和“this”之间包含相当多的空格 (4认同)