[C/C++] sstream library

Onam Kwon·2022년 12월 2일
0

C/C++

목록 보기
8/12

sstream / stringstream

  • C++ 라이브러리로 주어진 문자열에서 맞는 자료형에 맞춰 정보를 꺼낼때 사용함.
    • 공백 과 엔터 \n 를 제외하고 문자열에서 일치하는 자료형의 데이터를 추출한다.
  • ss.str("abc"): sstream변수 ss 를 "abc"로 초기화한다.
  • ss.str(): sstream변수 ss의 전체 스트링을 반환한다.

🔽main.cpp🔽

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

using namespace std;

int main() {
    int answer = 0;
    string my_string = "3 + 44 - 44 + 7";
    stringstream ss;

    /**
     * Initializing ss to my_string.
     */
    ss.str(my_string);
    cout<<"Before while loop:";
    cout<<ss.str()<<endl;

    // Initializing answer to the first segement of my_string.
    ss >> answer;
    
    /**
     * This while loop starts from second segement since answer took the first segement from above.
     */
    string ch;
    int cursor = 0;
    while(ss) {
        if(ch=="+") {
            answer += cursor;
        } else if(ch=="-") {
            answer -= cursor;
        }
        /**
         * Second segement of my_string goes to ch which is string type,
         * third segement of my_string goes to cursor which is int type.
         * And keep repeating it until end of the ss.
         */
        ss >> ch >> cursor;
    }

    /**
     * Above process does not change any to ss variable. 
     * ss.str() returns the entire string sentence. 
     */
    cout<<"After while loop: ";
    cout<<ss.str()<<endl;
    cout<<"Answer: "<<answer<<endl;
    return 0;
}

🔽Output🔽

Before while loop:3 + 44 - 44 + 7
After while loop: 3 + 44 - 44 + 7
Answer: 10
  • 주어진 string형 변수 my_string을 계산하는 프로그램을 만들때 위의 위의 방식으로 하면 편하게 만들수 있다.
    • my_string의 첫번째 변수는 answer에 초기화 한 후 while루프에서 앞으로 오는 변수 2개씩 나눠가며 처리한다.
    • my_string의 형태는 숫자, 연산자, 숫자, 연산자의 반복이므로 두번째부터 반복문에 넣어줌.
    • 두번째는 문자열형 ch, 세번째는 정수형 cursor 변수로 받아준다.
    • 네번째는 다시 반복하므로 ch, 다섯번째는 cursor 이런식으로 끝까지 반복.
  • 추가로 값을 추출한다고 해서 sstream형 변수 ss의 값이 변하지 않는다.

Github

profile
권오남 / Onam Kwon

0개의 댓글