
- istringstream 은 문자열 입력 스트림.
공백을 기준으로 문자열을 파싱하여 변수에 저장. ( cin 과 비슷하다. )
타입이 맞지 않을땐 0 을 리턴한다.
#include<iostream> #include<sstream> int main() { std::istringstream iss("this is string test haha"); std::string str, str1, str2; int inta; std::cout << iss.str() << std::endl; // 스트림 안에 있는 string 확인 std::cout << "입력 시작 " << std::endl; iss >> str >> str1 >> str2 >> inta; std::cout << "str : " << str << std::endl; std::cout << "str1 : " << str1 << std::endl; std::cout << "str2 : " << str2 << std::endl; std::cout << "inta : " << inta << std::endl; }
[ Output ]
this is string test haha
입력 시작
this
is
string
0
inta 가 0 이 나온 이유는 스트림에 "test"가 읽혔고 inta에 저장하려고 보니 inta 타입이 int 이기 때문에 타입이 맞지 않아 0을 리턴.
그렇다면 아래의 결과는 어떻게 될까?
#include<string> #include<iostream> #include<sstream> using namespace std; int main() { string str = "this is string test haha"; istringstream is(str); // 아래 두 줄 처럼 해도 된다. // istringstream is; // is.str(str); cout << "스트림에는 : " << is.str() << " 문자열이 있다." << endl; string num; while (is >> num) cout << num << endl; return 0; }
[ Output ]
더보기
스트림에는 : this is string test haha 문자열이 있다.
this
is
string
test
haha
while 문을 돌면서 스트림에 아무것도 없을때 빠져나온다.
[ ※ 참고 ]
std :: stringstream :: str
str() 은 두 가지 형태가 있다.
string str() const; (1) void str (const string& s); (2)
(1) 은 스트림 버퍼에 있는 string 을 리턴한다.
(2) 은 스트림에 인자로 받은 s를 set 해준다.
[ 예시 ]
ss.str ("Example string"); <--- (2) 번으로 사용. string temp = ss.str(); <----(1) 번으로 사용. cout << temp << '\n';
'Language & etc > Reference' 카테고리의 다른 글
assert 함수 (0) | 2022.04.17 |
---|---|
string 의 erase (0) | 2021.11.26 |
substr (0) | 2021.11.15 |