C++ I/O 및 파일 조작 - 6. 스트링 스트림 (String Streams)

2025. 3. 30. 00:49프로그래밍 언어/C++

 

📘 6. 스트링 스트림 (String Streams)

✅ 개요

C++의 스트링 스트림은 문자열을 스트림처럼 다루는 기능으로, <sstream> 헤더에서 제공됩니다.
마치 콘솔 입력/출력이나 파일 입출력처럼, 문자열을 대상으로 입력(input), 출력(output) 작업을 수행할 수 있어
데이터 파싱, 문자열 조립, 변환 등에 매우 유용하게 사용됩니다.


✅ 주요 클래스

클래스 이름 설명
std::istringstream 문자열을 입력 스트림처럼 처리 (파싱용)
std::ostringstream 출력을 문자열로 저장 (조립용)
std::stringstream 입력과 출력 모두 지원

✅ 예제 1: 문자열 파싱 (istringstream)

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

int main() {
    std::string data = "100 3.14 Hello";

    std::istringstream iss(data);

    int a;
    double b;
    std::string c;

    iss >> a >> b >> c;

    std::cout << "a = " << a << "\n";
    std::cout << "b = " << b << "\n";
    std::cout << "c = " << c << "\n";

    return 0;
}

📌 문자열을 공백 단위로 분리하여 각 변수에 저장합니다.


✅ 예제 2: 문자열 조립 (ostringstream)

#include <iostream>
#include <sstream>

int main() {
    int year = 2025;
    std::string name = "ChatGPT";

    std::ostringstream oss;
    oss << name << " © " << year;

    std::string result = oss.str();  // 조립된 문자열 가져오기

    std::cout << result << std::endl;

    return 0;
}

📌 여러 개의 값을 연결하여 문자열로 만드는 데 유용합니다.


✅ 예제 3: 입력과 출력 동시 사용 (stringstream)

#include <iostream>
#include <sstream>

int main() {
    std::stringstream ss;

    // 출력
    ss << "123 4.56 GPT";

    // 입력
    int i;
    double d;
    std::string word;

    ss >> i >> d >> word;

    std::cout << "i = " << i << ", d = " << d << ", word = " << word << std::endl;

    return 0;
}

📌 하나의 객체로 문자열을 조립하고 파싱할 수 있어 매우 유연합니다.


✅ 스트림 상태 초기화

stringstream 객체는 재사용 시 반드시 상태를 초기화해야 예기치 않은 오류를 방지할 수 있습니다.

#include <iostream>
#include <sstream>

int main() {
    std::stringstream ss;
    ss << "123";

    int x;
    ss >> x;

    // 스트림 초기화
    ss.clear();      // 오류 상태 리셋
    ss.str("");      // 내부 문자열 제거

    ss << "456";
    ss >> x;

    std::cout << "x = " << x << std::endl;

    return 0;
}

📌 clear()는 스트림 상태(eof, fail 등)를 초기화하고, str("")은 내부 버퍼 문자열을 비웁니다.


✅ 오류 처리: 컴파일 vs 런타임

구분 설명
컴파일 오류 문법 오류, 잘못된 타입 사용 등 → 코드 작성 시점에 감지됨
런타임 오류 데이터 형식 불일치, 스트림 오류 등 → 실행 도중 발생

📌 런타임 오류 예시:

std::istringstream iss("abc");
int number;
iss >> number;

if (iss.fail()) {
    std::cerr << "숫자 변환 실패!" << std::endl;
}
  • "abc"는 정수로 변환할 수 없기 때문에 fail() 상태가 발생합니다.
  • 스트림 사용 시 fail(), eof() 등 상태 점검은 필수입니다.

✅ 활용 예시

  • 사용자 입력값 파싱 및 검증
  • 공백/쉼표/탭 구분 데이터 처리 (CSV 등)
  • 복잡한 문자열 조립 (로그, 파일 이름 등)
  • 숫자 → 문자열 변환 (std::to_string() 대체)
  • 문자열 → 숫자 변환 (std::stoi() 대체)