代码之家  ›  专栏  ›  技术社区  ›  Jason R. Mick

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

  •  60
  • Jason R. Mick  · 技术社区  · 14 年前

    不要混淆如何按解析方式拆分字符串,例如:
    Split a string in 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() 方法,但我想知道是否有任何更短/更优雅(例如,更多的PythoNoice,虽然显然是三重引号等,在C++中不支持)将C++中的字符串断开到多行,以便可读性。

    当您将长字符串文本传递给函数(例如句子)时,这一点尤其可取。

    3 回复  |  直到 14 年前
        1
  •  97
  •   Salman A    14 年前

    不要把任何东西放在绳子之间。C++词法阶段的一部分是将相邻的字符串文字(甚至在新行和注释)组合成单个文字。

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

    请注意,如果您希望在文字中添加新行,则必须自己添加:

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

    如果你想混合 #define d整型常量到文字中,必须使用一些宏:

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

    其中有一些奇怪之处,因为字符串化处理器操作程序的工作方式,所以需要两个级别的宏来获取 TWO 变成字符串文字。

        2
  •  9
  •   Matt K    14 年前

    它们都是文字吗?用空格分隔两个字符串文本与串联相同: "abc" "123" 是一样的 "abc123" . 这适用于直C和C++。

        3
  •  4
  •   rmeador    14 年前

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

    #include <iostream>
    #include <string>
    
    int main ()
    {
        std::string str = "hello world\
        this seems to work";
    
        std::cout << str;
        return 0;
    }