C++
[ C++ ] stringstream 사용 방법
통통푸딩
2021. 1. 24. 20:12
반응형
문자열을 나누는 stringstream
C++에서 stringstream은 주어진 문자열에서 필요한 자료형에 맞는 정보를 꺼낼 때 유용하게 사용된다.
stringstream에서 공백과 '\n'을 제외하고 문자열에서 맞는 자료형의 정보를 빼낸다.
#include <sstream> 전처리 헤더를 포함해야한다.
예제를 보자!
#include <string>
#include <sstream>
#include <iostream>
int main() {
int num;
string s;
string str1 = "123 456", str2 = "hello world!";
stringstream stream1, stream2(str2);
//초기화
stream1.str(str1);
while(stream1 >> num){
cout << num << endl;
}
while(stream2 >> s){
cout<<s<<endl;
}
}
istringstream
istringstream은 문자열을 여러 개의 문자열로 분리할 때 편리하다.
#include <string>
#include <sstream>
using namespace std;
int main() {
string str = "abc def gg 11";
string s[4];
istringstream stt(str);
stt >> s[0] >> s[1] >> s[2] >> s[3];
}
반응형