stringstreamstringstream은 입출력(std::ios::in | std::ios::out)이 모두 가능한 문자열 스트림 클래스다. 즉, stringstream 객체를 사용하면 문자열을 읽고 쓰는 작업을 동시에 수행할 수 있다.
#include <iostream>
#include <sstream>
int main() {
std::stringstream ss;
// 문자열 쓰기
ss << "123 456 789";
// 문자열 읽기
int a, b, c;
ss >> a >> b >> c;
std::cout << a << " " << b << " " << c << std::endl;
return 0;
}
stringstream 객체는 입력 및 출력이 모두 가능하므로, 한 개의 객체로 << 연산자로 데이터를 쓰고, >> 연산자로 데이터를 읽을 수 있다.istringstreamistringstream은 입력 전용(std::ios::in) 문자열 스트림 클래스다. 즉, 기존 문자열을 읽기 전용 스트림으로 사용할 때 적합하다.
#include <iostream>
#include <sstream>
int main() {
std::string data = "123 456 789";
std::istringstream iss(data);
int a, b, c;
iss >> a >> b >> c;
std::cout << a << " " << b << " " << c << std::endl;
return 0;
}
istringstream은 읽기 전용 스트림이므로, << 연산자로 데이터를 쓸 수 없다.ostringstreamostringstream는 출력 전용(std::ios::out) 문자열 스트림으로, 문자열을 생성하는 데 사용된다. 즉, 데이터를 문자열로 변환하고 이를 하나의 문자열로 조합할 때 유용하다.
#include <iostream>
#include <sstream>
int main() {
std::ostringstream oss;
// 여러 데이터를 하나의 문자열로 조합
oss << "Hello, " << "world! " << 2024;
// 최종 문자열 가져오기
std::string result = oss.str();
std::cout << result << std::endl;
return 0;
}
<< 연산자로 데이터를 추가할 수 있다..str() 메서드를 통해 최종 문자열을 가져올 수 있다.