c++ stringstream

gyubong park·2022년 1월 17일
0

stringstream은 문자열 시퀀스를 포함하는 string buffer를 사용한다. 이러한 문자열 시퀀스는 str이라는 멤버를 사용하여 문자열 객체로 직접 접근할수 있다.
iostream을 상속받기 때눔에 stream에서 문자들을 삽입 혹은 추출가능하다.

stringstream 사용 예1

stringstream은 문자열을 필요한 자료형으로 꺼내서 쓸때 유용하다.

#include <iostream>
#include <sstream>

int main() {
    std::string s = "123 456";
    std::stringstream ss;
    ss.str(s);

    int num;
    while(ss >> num)
    {
        std::cout << num << std::endl;
    }

    return 0;
}

결과값 출력

123
456

Process finished with exit code 0

stringstream 사용 예2

초기화

#include <iostream>
#include <sstream>

int main() {
    std::string s = "aaaaa";
    std::stringstream ss;
    ss.str(s);
    std::cout << "초기화 전 : " << ss.str() << std::endl;

    ss.str("");
    ss.clear();
    std::cout << "초기화 후 : " << ss.str() << std::endl;

    return 0;
}

결과값 출력

초기화 전 : aaaaa
초기화 후 : 

Process finished with exit code 0
profile
초보 개발자

0개의 댓글