C++
[C++] stringstream
dh_0e
2024. 7. 22. 21:31
stringstream
- 문자열에서 동작하는 스트림 클래스
- 입력 스트림인 istringstream, 출력 스트림인 ostringstream의 기능을 둘 다 포함하고 있음
- 공백이나 '\n' 개행문자를 기준으로 값을 분리해줌
- string type의 문자열에서 원하는 자료형의 데이터를 추출할 수 있게 해줌
- <sstream> 헤더 파일을 선언하고 사용
문자열을 공백, '\n'을 기준으로 분리
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string n;
string str = "abc d ef\n gh i1 2 3";
stringstream stream;
stream.str(str); // = "stream=str"
while(stream >> n)
{
cout << n << endl; // abc d ef gh i1 2 3
}
return 0;
}
문자열에서 int type 추출
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
string str = "111 -222\n 11+100 ++1000";
stringstream stream;
stream.str(str); // = "stream=str"
while(stream >> n)
{
cout << n << endl; // 111 -222 11 100
}
return 0;
}
- -222와 +100도 인식하지만 ++1000은 +를 문자로 인식하여 추출하지 않는다.