1、头文件
#include <sstream>
2、作用
istringstream类用于执行C++风格的字符串流的输入操作。
ostringstream类用于执行C++风格的字符串流的输出操作。
stringstream类同时可以支持C++风格的串流的输入输出操作。
3、代码
1) istringstream
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string tmp="I am a 18 boy";
istringstream is(tmp);
string s;
while(is>>s)
cout << " " << s;
cout << endl;
std::string stringvalues = "125 320 512 750 333";
std::istringstream iss (stringvalues);
for (int n=0; n<5; n++)
{
int val;
iss >> val;
std::cout << val*2 << '\n';
}
return 1;
}
I am a 18 boy
250
640
1024
1500
666
2) ostringstream
// ostringstream constructor
#include <iostream> // std::cout, std::ios
#include <sstream> // std::ostringstream
int main () {
std::ostringstream foo; // out
std::ostringstream bar (std::ostringstream::ate); // out|ate
foo.str("Test string");
bar.str("Test string");
foo << 101;
bar << 101;
std::cout << foo.str() << '\n';
std::cout << bar.str() << '\n';
return 0;
}
101t string
Test string101
3) stringstream
// swapping ostringstream objects
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
int main () {
std::stringstream ss;
ss << 100 << ' ' << 200;
int foo,bar;
ss >> foo >> bar;
std::cout << "foo: " << foo << '\n';
std::cout << "bar: " << bar << '\n';
std::string stringvalues = "125 320 512 750 333";
std::stringstream iss (stringvalues);
for (int n=0; n<5; n++)
{
int val;
iss >> val;
std::cout << val*2 << '\n';
}
return 0;
}
foo: 100
bar: 200
250
640
1024
1500
666