stringstream, istringstream, ostringstream

김민수·2025년 2월 10일

C++

목록 보기
65/68

1. stringstream

stringstream입출력(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 객체는 입력 및 출력이 모두 가능하므로, 한 개의 객체로 << 연산자로 데이터를 쓰고, >> 연산자로 데이터를 읽을 수 있다.

2. istringstream

istringstream입력 전용(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읽기 전용 스트림이므로, << 연산자로 데이터를 쓸 수 없다.
  • 주어진 문자열을 토큰화하여 변환하거나, 특정 형식의 데이터를 추출하는 데 유용하다.

3. ostringstream

ostringstream출력 전용(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() 메서드를 통해 최종 문자열을 가져올 수 있다.
  • 주로 문자열을 동적으로 구성할 때 유용하다.
profile
안녕하세요

0개의 댓글