web-dev-qa-db-ja.com

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++の文字列を複数行に分割する方法。

これが特に望ましいのは、長い文字列リテラルを関数(文など)に渡す場合です。

63
Jason R. Mick

文字列の間に何も入れないでください。 C++の字句解析段階の一部は、隣接する文字列リテラルを(改行やコメントの上でも)1つのリテラルに結合することです。

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

#defined整数定数をリテラルに混ぜたい場合は、いくつかのマクロを使用する必要があります。

#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レベルのマクロが必要です。

103
Eclipse

両方ともリテラルですか? 2つの文字列リテラルを空白で区切るのは、連結と同じです。"abc" "123""abc123"と同じです。これは、ストレートCおよびC++に適用されます。

9
mkb

GCCの拡張機能か標準かはわかりませんが、行をバックスラッシュで終了することで文字列リテラルを継続できるようです(C++のこのマナーではほとんどのタイプの行を拡張できるように、たとえば、複数行にわたるマクロ)。

#include <iostream>
#include <string>

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

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