c++) string stream
https://www.cplusplus.com/reference/sstream/stringstream/
stringstream - C++ Reference
class std::stringstream typedef basic_stringstream stringstream; Input/output string stream Stream class to operate on strings. Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be a
www.cplusplus.com
문자열을 다룰때 유용하다.
iostream이 input,output의 stream이라면
stringstream은 string의 stream.
#include <sstream> 포함시켜야 사용할수 있다.
문자열에서 내가 원하는 자료들만 빼내는데 아주 유용하다.
1. stringstream은 공백과 개행을 무시하고 가져온다
2. stringstream.str()은 stringstream을 초기화 할수도 있고, 현재 stringstream에 있는 문자열을 갖고오기도 한다.
stringstream을 초기화 할때는 ss.str("")
3. stringstream은 특정 자료형을 빼낼때도 유용하다.
>> 연산자로 stream에서 문자열을 추출할때 추출받는 변수의 자료형에 따라 달라진다.
여기서는 문자열을 추출받는 token이 string형이기 때문에 hello my name is가 추출된다.
그런데 token의 자료형을 int로 바꾸면 아무것도 추출되지 않는다.
위와 같이 str이 132 33 hello이고, token의 자료형이 int라면 int자료형인 132 33까지만 추출되고 뒤의 hello는 추출되지 않는다.
주의할점은 이렇게 문자를 추출했더라도 stringstream은 그대로다.
4. get(), unget()
get은 stream에서 커서를 하나씩 앞으로 옮기고 값을 반환한다
unget은 stream의 커서를 다시 앞으로 되돌린다.
(char)를 때고 출력하면 아스키코드 값이 출력된다.
5. char형 하나씩 추출
2021.10.12 추가
char형 하나씩 추출할때 아래와 같이 추출하지 말자.
찾아봐도 이유를 모르겠는데 이 문제(https://tose33.tistory.com/396)가 이것때문에 계속 틀림.
stringstream ss(str);
char token;
while(ss >> token)
{
...
}
6. getline
delim을 지정해서 해당 문자가 나오기 전까지의 string을 구한다.
getline(탐색할 문자열, 저장 장소, delim)