[c++] C++에서의 여러 문자열을 합치는 방법

다음은 + 연산자를 사용하여 문자열을 결합하는 기본적인 예시입니다.

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello, ";
    std::string str2 = "world!";
    std::string result = str1 + str2;
    
    std::cout << result << std::endl;
    
    return 0;
}

이 코드는 “Hello, world!”를 출력합니다.

또 다른 방법은 std::stringstream을 사용하는 것입니다. 이 방법은 문자열을 결합할 때 유용합니다.

#include <iostream>
#include <string>
#include <sstream>

int main() {
    std::stringstream ss;
    std::string str1 = "Hello, ";
    std::string str2 = "world!";
    
    ss << str1 << str2;
    std::string result = ss.str();
    
    std::cout << result << std::endl;
    
    return 0;
}

std::stringstream을 사용하면 문자열을 결합하기 위해 + 연산자를 여러 번 사용할 필요가 없어 편리합니다.

그 외에도 C++에서는 문자열을 결합하는 다른 여러 가지 방법이 있지만, 이 두 가지 방법이 가장 널리 쓰이는 방법입니다.

이러한 문자열 결합의 다양한 방법은 C++ 표준 라이브러리 문서에서 찾아볼 수 있습니다.