문제

C#구문 할 수있는 기능을 연결하는 많은 데이터 유형에 함께 1 라인입니다.

string s = new String();
s += "Hello world, " + myInt + niceToSeeYouString;
s += someChar1 + interestingDecimal + someChar2;

무엇에 해당하는 것에서는 C++?로 볼 수 있습니다,당신이해야 할 모든 것에 별도의 선로 그것을 지원하지 않는 여러 문자열 변수를+연산자입니다.이 확인되지만,으로 보이지 않는 깔끔합니다.

string s;
s += "Hello world, " + "nice to see you, " + "or not.";

위의 코드를 생산하는 오류가 있습니다.

도움이 되었습니까?

해결책

#include <sstream>
#include <string>

std::stringstream ss;
ss << "Hello, world, " << myInt << niceToSeeYouString;
std::string s = ss.str();

Herb Sutter의 이번 주 전문가 기사를 살펴보십시오. 매너 농장의 끈 형성자

다른 팁

5 년 후 아무도 언급하지 않았습니다 .append?

#include <string>

std::string s;
s.append("Hello world, ");
s.append("nice to see you, ");
s.append("or not.");
s += "Hello world, " + "nice to see you, " + "or not.";

그 문자 배열 리터럴은 c ++ std :: 문자열이 아닙니다 - 당신은 그것들을 변환 할 것입니다.

s += string("Hello world, ") + string("nice to see you, ") + string("or not.");

ints (또는 기타 스트림 가능한 유형)를 변환하려면 부스트 lexical_cast를 사용하거나 자신의 기능을 제공 할 수 있습니다.

template <typename T>
string Str( const T & t ) {
   ostringstream os;
   os << t;
   return os.str();
}

이제 다음과 같은 말을 할 수 있습니다.

string s = "The meaning is " + Str( 42 );

코드는 다음과 같이 작성할 수 있습니다1,

s = "Hello world," "nice to see you," "or not."

...하지만 그게 당신이 찾고있는 것 같아요. 귀하의 경우, 당신은 아마도 스트림을 찾고있을 것입니다.

std::stringstream ss;
ss << "Hello world, " << 42 << "nice to see you.";
std::string s = ss.str();

1 "작성할 수 있습니다": 이것은 문자열 리터럴에만 작동합니다. 연결은 컴파일러에 의해 수행됩니다.

C ++ 14 사용자 정의 리터럴 사용 및 std::to_string 코드가 더 쉬워집니다.

using namespace std::literals::string_literals;
std::string str;
str += "Hello World, "s + "nice to see you, "s + "or not"s;
str += "Hello World, "s + std::to_string(my_int) + other_string;

문자 리터럴 연결은 컴파일 시간에 수행 할 수 있습니다. 그냥 제거하십시오 +.

str += "Hello World, " "nice to see you, " "or not";

더 한 줄로 더 많은 솔루션을 제공하려면 : 기능 concat "클래식"StringStream 기반 솔루션을 단일 진술. 다양한 템플릿과 완벽한 전달을 기반으로합니다.


용법:

std::string s = concat(someObject, " Hello, ", 42, " I concatenate", anyStreamableType);

구현:

void addToStream(std::ostringstream&)
{
}

template<typename T, typename... Args>
void addToStream(std::ostringstream& a_stream, T&& a_value, Args&&... a_args)
{
    a_stream << std::forward<T>(a_value);
    addToStream(a_stream, std::forward<Args>(a_args)...);
}

template<typename... Args>
std::string concat(Args&&... a_args)
{
    std::ostringstream s;
    addToStream(s, std::forward<Args>(a_args)...);
    return s.str();
}

부스트 :: 형식

또는 std :: stringstream

std::stringstream msg;
msg << "Hello world, " << myInt  << niceToSeeYouString;
msg.str(); // returns std::string object

그만큼 실제 문제 문자 리터럴을 연결하는 것이 었습니다 + C ++에서 실패 :

string s;
s += "Hello world, " + "nice to see you, " + "or not.";
위의 코드는 오류가 발생합니다.

C ++ (C)에서는 문자 리터럴을 서로 바로 옆에 배치하여 문자 리터를 연결합니다.

string s0 = "Hello world, " "nice to see you, " "or not.";
string s1 = "Hello world, " /*same*/ "nice to see you, " /*result*/ "or not.";
string s2 = 
    "Hello world, " /*line breaks in source code as well as*/ 
    "nice to see you, " /*comments don't matter*/ 
    "or not.";

매크로에서 코드를 생성하는 경우에 의미가 있습니다.

#define TRACE(arg) cout << #arg ":" << (arg) << endl;

... 이렇게 사용할 수있는 간단한 매크로

int a = 5;
TRACE(a)
a += 7;
TRACE(a)
TRACE(a+7)
TRACE(17*11)

(라이브 데모 ...)

또는 사용을 고집하면 + 문자열 리터럴 용 (이미 제안 된 바와 같이 coundscore_d):

string s = string("Hello world, ")+"nice to see you, "+"or not.";

다른 솔루션은 문자열과 a를 결합합니다 const char* 각 연결 단계에 대해

string s;
s += "Hello world, "
s += "nice to see you, "
s += "or not.";
auto s = string("one").append("two").append("three")

이랑 {fmt} 라이브러리 넌 할 수있어:

auto s = fmt::format("{}{}{}", "Hello world, ", myInt, niceToSeeYouString);

도서관의 하위 집합은 표준화를 위해 제안됩니다. P0645 텍스트 형식 그리고 받아 들여지면 위는 다음과 같습니다.

auto s = std::format("{}{}{}", "Hello world, ", myInt, niceToSeeYouString);

부인 성명: 저는 {fmt} 라이브러리의 저자입니다.

문자열에 동결하려는 모든 데이터 유형에 대해 연산자+()를 정의해야하지만, Operator <<이 대부분의 유형에 대해 정의되므로 std :: stringstream을 사용해야합니다.

젠장, 50 초로 이겼다 ...

당신이 쓸 때 +=, 그것은 C#과 거의 동일하게 보입니다.

string s("Some initial data. "); int i = 5;
s = s + "Hello world, " + "nice to see you, " + to_string(i) + "\n";

다른 사람들이 말했듯이 OP 코드의 주요 문제는 운영자가 + 연결하지 않습니다 const char *; 그것은 함께 작동합니다 std::string, 그렇지만.

다음은 C ++ 11 Lambdas와 for_each 그리고 제공 할 수 있습니다 separator 문자열을 분리하려면 :

#include <vector>
#include <algorithm>
#include <iterator>
#include <sstream>

string join(const string& separator,
            const vector<string>& strings)
{
    if (strings.empty())
        return "";

    if (strings.size() == 1)
        return strings[0];

    stringstream ss;
    ss << strings[0];

    auto aggregate = [&ss, &separator](const string& s) { ss << separator << s; };
    for_each(begin(strings) + 1, end(strings), aggregate);

    return ss.str();
}

용법:

std::vector<std::string> strings { "a", "b", "c" };
std::string joinedStrings = join(", ", strings);

적어도 내 컴퓨터에서 빠른 테스트를 마친 후 (선형 적으로) 확장하는 것 같습니다. 다음은 내가 작성한 빠른 테스트입니다.

#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <chrono>

using namespace std;

string join(const string& separator,
            const vector<string>& strings)
{
    if (strings.empty())
        return "";

    if (strings.size() == 1)
        return strings[0];

    stringstream ss;
    ss << strings[0];

    auto aggregate = [&ss, &separator](const string& s) { ss << separator << s; };
    for_each(begin(strings) + 1, end(strings), aggregate);

    return ss.str();
}

int main()
{
    const int reps = 1000;
    const string sep = ", ";
    auto generator = [](){return "abcde";};

    vector<string> strings10(10);
    generate(begin(strings10), end(strings10), generator);

    vector<string> strings100(100);
    generate(begin(strings100), end(strings100), generator);

    vector<string> strings1000(1000);
    generate(begin(strings1000), end(strings1000), generator);

    vector<string> strings10000(10000);
    generate(begin(strings10000), end(strings10000), generator);

    auto t1 = chrono::system_clock::now();
    for(int i = 0; i<reps; ++i)
    {
        join(sep, strings10);
    }

    auto t2 = chrono::system_clock::now();
    for(int i = 0; i<reps; ++i)
    {
        join(sep, strings100);
    }

    auto t3 = chrono::system_clock::now();
    for(int i = 0; i<reps; ++i)
    {
        join(sep, strings1000);
    }

    auto t4 = chrono::system_clock::now();
    for(int i = 0; i<reps; ++i)
    {
        join(sep, strings10000);
    }

    auto t5 = chrono::system_clock::now();

    auto d1 = chrono::duration_cast<chrono::milliseconds>(t2 - t1);
    auto d2 = chrono::duration_cast<chrono::milliseconds>(t3 - t2);
    auto d3 = chrono::duration_cast<chrono::milliseconds>(t4 - t3);
    auto d4 = chrono::duration_cast<chrono::milliseconds>(t5 - t4);

    cout << "join(10)   : " << d1.count() << endl;
    cout << "join(100)  : " << d2.count() << endl;
    cout << "join(1000) : " << d3.count() << endl;
    cout << "join(10000): " << d4.count() << endl;
}

결과 (밀리 초) :

join(10)   : 2
join(100)  : 10
join(1000) : 91
join(10000): 898

어쩌면 당신은 내 "스 트리머"솔루션을 좋아할 것입니다.

#include <iostream>
#include <sstream>
using namespace std;

class Streamer // class for one line string generation
{
public:

    Streamer& clear() // clear content
    {
        ss.str(""); // set to empty string
        ss.clear(); // clear error flags
        return *this;
    }

    template <typename T>
    friend Streamer& operator<<(Streamer& streamer,T str); // add to streamer

    string str() // get current string
    { return ss.str();}

private:
    stringstream ss;
};

template <typename T>
Streamer& operator<<(Streamer& streamer,T str)
{ streamer.ss<<str;return streamer;}

Streamer streamer; // make this a global variable


class MyTestClass // just a test class
{
public:
    MyTestClass() : data(0.12345){}
    friend ostream& operator<<(ostream& os,const MyTestClass& myClass);
private:
    double data;
};

ostream& operator<<(ostream& os,const MyTestClass& myClass) // print test class
{ return os<<myClass.data;}


int main()
{
    int i=0;
    string s1=(streamer.clear()<<"foo"<<"bar"<<"test").str();                      // test strings
    string s2=(streamer.clear()<<"i:"<<i++<<" "<<i++<<" "<<i++<<" "<<0.666).str(); // test numbers
    string s3=(streamer.clear()<<"test class:"<<MyTestClass()).str();              // test with test class
    cout<<"s1: '"<<s1<<"'"<<endl;
    cout<<"s2: '"<<s2<<"'"<<endl;
    cout<<"s3: '"<<s3<<"'"<<endl;
}

이와 관련 하여이 헤더를 사용할 수 있습니다. https://github.com/theypsilon/concat

using namespace concat;

assert(concat(1,2,3,4,5) == "12345");

후드 아래에서 당신은 std :: ostringstream을 사용하게됩니다.

당신이 기꺼이 사용한다면 c++11 당신은 활용할 수 있습니다 사용자 정의 문자열 리터럴 플러스 연산자에 과부하가되는 두 개의 기능 템플릿을 정의합니다. std::string 물체와 다른 객체. 유일한 함정은 std::string, 그렇지 않으면 컴파일러는 어떤 연산자를 사용할 것인지 모릅니다. 템플릿을 사용하여이를 수행 할 수 있습니다 std::enable_if ~에서 type_traits. 그 후 문자열은 Java 또는 C#처럼 행동합니다. 자세한 내용은 내 예제 구현을 참조하십시오.

메인 코드

#include <iostream>
#include "c_sharp_strings.hpp"

using namespace std;

int main()
{
    int i = 0;
    float f = 0.4;
    double d = 1.3e-2;
    string s;
    s += "Hello world, "_ + "nice to see you. "_ + i
            + " "_ + 47 + " "_ + f + ',' + d;
    cout << s << endl;
    return 0;
}

C_SHARP_STRINGS.HPP 파일

이 문자열을 갖고 싶은 모든 장소 에이 헤더 파일을 포함시킵니다.

#ifndef C_SHARP_STRING_H_INCLUDED
#define C_SHARP_STRING_H_INCLUDED

#include <type_traits>
#include <string>

inline std::string operator "" _(const char a[], long unsigned int i)
{
    return std::string(a);
}

template<typename T> inline
typename std::enable_if<!std::is_same<std::string, T>::value &&
                        !std::is_same<char, T>::value &&
                        !std::is_same<const char*, T>::value, std::string>::type
operator+ (std::string s, T i)
{
    return s + std::to_string(i);
}

template<typename T> inline
typename std::enable_if<!std::is_same<std::string, T>::value &&
                        !std::is_same<char, T>::value &&
                        !std::is_same<const char*, T>::value, std::string>::type
operator+ (T i, std::string s)
{
    return std::to_string(i) + s;
}

#endif // C_SHARP_STRING_H_INCLUDED

또한 문자열 클래스를 "확장"하고 선호하는 연산자 (<<, &, | 등 ...)를 선택할 수 있습니다.

연산자를 사용한 코드는 다음과 같습니다. << 스트림과 충돌이 없음을 보여줍니다.

참고 : S1.Reserve (30)를 무례한 경우, 3 개의 새로운 () 운영자 요청 만 있습니다 (S1의 경우 1, S2의 경우 1, 예비는 1 개, 구체적으로 구축기 시간에 예약 할 수는 없습니다). Reserve가 없으면 S1은 성장함에 따라 더 많은 메모리를 요청해야하므로 컴파일러 구현 성장 계수에 따라 다릅니다 (이 예에서는 Mine이 1.5, 5 New () 호출 인 것 같습니다).

namespace perso {
class string:public std::string {
public:
    string(): std::string(){}

    template<typename T>
    string(const T v): std::string(v) {}

    template<typename T>
    string& operator<<(const T s){
        *this+=s;
        return *this;
    }
};
}

using namespace std;

int main()
{
    using string = perso::string;
    string s1, s2="she";
    //s1.reserve(30);
    s1 << "no " << "sunshine when " << s2 << '\'' << 's' << " gone";
    cout << "Aint't "<< s1 << " ..." <<  endl;

    return 0;
}

이와 같은 것이 저에게 효과적입니다

namespace detail {
    void concat_impl(std::ostream&) { /* do nothing */ }

    template<typename T, typename ...Args>
    void concat_impl(std::ostream& os, const T& t, Args&&... args)
    {
        os << t;
        concat_impl(os, std::forward<Args>(args)...);
    }
} /* namespace detail */

template<typename ...Args>
std::string concat(Args&&... args)
{
    std::ostringstream os;
    detail::concat_impl(os, std::forward<Args>(args)...);
    return os.str();
}
// ...
std::string s{"Hello World, "};
s = concat(s, myInt, niceToSeeYouString, myChar, myFoo);

위의 솔루션을 바탕으로 프로젝트가 인생을 쉽게 만들기 위해 Var_string 클래스를 만들었습니다. 예 :

var_string x("abc %d %s", 123, "def");
std::string y = (std::string)x;
const char *z = x.c_str();

수업 자체 :

#include <stdlib.h>
#include <stdarg.h>

class var_string
{
public:
    var_string(const char *cmd, ...)
    {
        va_list args;
        va_start(args, cmd);
        vsnprintf(buffer, sizeof(buffer) - 1, cmd, args);
    }

    ~var_string() {}

    operator std::string()
    {
        return std::string(buffer);
    }

    operator char*()
    {
        return buffer;
    }

    const char *c_str()
    {
        return buffer;
    }

    int system()
    {
        return ::system(buffer);
    }
private:
    char buffer[4096];
};

C ++에 더 나은 것이 있을지 여전히 궁금하십니까?

C11에서 :

void printMessage(std::string&& message) {
    std::cout << message << std::endl;
    return message;
}

이렇게하면 다음과 같은 기능 호출을 만들 수 있습니다.

printMessage("message number : " + std::to_string(id));

인쇄 : 메시지 번호 : 10

여기에는 한-라이너 솔루션:

#include <iostream>
#include <string>

int main() {
  std::string s = std::string("Hi") + " there" + " friends";
  std::cout << s << std::endl;

  std::string r = std::string("Magic number: ") + std::to_string(13) + "!";
  std::cout << r << std::endl;

  return 0;
}

비록 그것이 작은 조금 못생긴 생각,그것의 연락처 정보를 얻을 고양이에서는 C++.

우리는 주조 첫 번째 인수 std::string 다음을 사용하여(왼쪽에서 오른쪽)평가는 순서 operator+ 연산자입니다 항상 std::string.이러한 방식으로,우리는 연결 std::string 에서 왼쪽으로 const char * 피연산자에 바로 돌아와 다른 std::string, css 효과가 있습니다.

참고:거기에 몇 가지 옵션에 대한 권리 연산자를 포함 const char *, std::string, 고 char.

그것은 당신이 여부를 결정하는 매직 번호는 13 6227020800.

Lambda 기능을 사용하는 간단한 사전 영양소 매크로가있는 StringStream은 다음과 같습니다.

#include <sstream>
#define make_string(args) []{std::stringstream ss; ss << args; return ss;}() 

그리고

auto str = make_string("hello" << " there" << 10 << '$');

이것은 나를 위해 작동합니다 :

#include <iostream>

using namespace std;

#define CONCAT2(a,b)     string(a)+string(b)
#define CONCAT3(a,b,c)   string(a)+string(b)+string(c)
#define CONCAT4(a,b,c,d) string(a)+string(b)+string(c)+string(d)

#define HOMEDIR "c:\\example"

int main()
{

    const char* filename = "myfile";

    string path = CONCAT4(HOMEDIR,"\\",filename,".txt");

    cout << path;
    return 0;
}

산출:

c:\example\myfile.txt

+=를 피하려고 했습니까? 대신 var = var +를 사용하십시오 ... 그것은 나를 위해 일했습니다.

#include <iostream.h> // for string

string myName = "";
int _age = 30;
myName = myName + "Vincent" + "Thorpe" + 30 + " " + 2019;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top