C++/Library
2021. 3. 26. 15:28
sstream
<sstream>
라이브러리stringstream
의 약자이다.<<
: insertion operator>>
: extraction operator
상속 관계
istringstream
,ostringstream
,stringstream
은 비슷하지만 약간 다른 부분이 존재한다.istringstream
에<<
연산자는 정의되어있지 않다.ostringstream
에>>
연산자는 정의되어있지 않다.
<iosfwd>
using istringstream = basic_istringstream<char, char_traits<char>, allocator<char>>; using ostringstream = basic_ostringstream<char, char_traits<char>, allocator<char>>; using stringstream = basic_stringstream<char, char_traits<char>, allocator<char>>;
<sstream>
// CLASS TEMPLATE basic_istringstream template <class _Elem, class _Traits, class _Alloc> class basic_istringstream : public basic_istream<_Elem, _Traits> { // input stream associated with a character array }; // CLASS TEMPLATE basic_ostringstream template <class _Elem, class _Traits, class _Alloc> class basic_ostringstream : public basic_ostream<_Elem, _Traits> { // output stream associated with a character array } // CLASS TEMPLATE basic_stringstream template <class _Elem, class _Traits, class _Alloc> class basic_stringstream : public basic_iostream<_Elem, _Traits> { // input/output stream associated with a character array }
기본 예제
stringstream
사용#include <iostream> #include <sstream> int main() { using namespace std; stringstream ss; ss << "Hello, World"; ss << '!'; string str; ss >> str; cout << str << endl; ss.str("Hello World!"); str = ss.str(); cout << str << endl; ss.str(""); cout << boolalpha << ss.str().empty() << endl; } /* stdout stderr Hello, Hello World! true */
숫자 넣기
#include <iostream> #include <sstream> int main() { using namespace std; stringstream ss; ss << "12345 67.89"; int i; double d; ss >> i >> d; cout << i << '|' << d << endl; }
/* stdout stderr
12345|67.89
*/
- `istringstream`, `ostringstream` 사용
```c++
#include <iostream>
#include <string>
#include <sstream>
template <typename T>
std::string ToString(T x)
{
std::ostringstream osstream;
osstream << x;
return osstream.str();
}
template <typename T>
bool FromString(const std::string& str, T& x)
{
std::istringstream isstream(str);
return (isstream >> x ? true : false);
}
int main()
{
using namespace std;
string my_str(ToString(3.141592));
cout << my_str << endl;
double d;
if (FromString(my_str, d))
cout << d << endl;
else
cout << "Cannot conver string to double\n";
if (FromString("Hello", d))
cout << d << endl;
else
cout << "Cannot conver string to double\n";
}
/* stdout stderr
3.14159
3.14159
Cannot conver string to double
*/
'C++ > Library' 카테고리의 다른 글
C++ istream (0) | 2021.03.29 |
---|---|
C++ wstring (0) | 2021.03.26 |
C++ string (0) | 2021.03.26 |
C++ STL 알고리즘 (Algorithms) (0) | 2021.03.26 |
C++ STL 반복자 (Iterators) (0) | 2021.03.26 |