안녕 세상아,

[c++/sstream] 문자열 공백 기준으로 자르기 본문

c++ 개념

[c++/sstream] 문자열 공백 기준으로 자르기

돈 많은 백수가 되고싶다 2023. 5. 16. 15:53

stringstream은 공백 기준으로 문자열을 자를 때 사용할 수 있다. 

stringstream을 사용하기 위해서는 sstream 헤더를 include해야한다. #include <sstream>

 

공백 기준으로 문자열을 자를 때 뿐만 아니라 문자열에서 int값을 찾을 때도 사용된다. 

 

<공백 기준으로 문자열 자르기>

#include <sstream>
#include <iostream>

int main() {
    // 공백 기준 문자열 자르기
    string s = "abc def ghi";
    
    stringstream ss(s);
    ss.str(s);

    string word;
    while(ss >> word) {
        cout << word;
    }
 }   

// 출력 내용
   abc
   def
   ghi