C++詳解(7) 字串流
阿新 • • 發佈:2020-12-09
- 基本使用
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
// 字串流是在記憶體內進行操作
ostringstream oss; // 定義一個字串輸入流
oss << "hello world!" << endl;
cout << oss.str() << endl; //用.str()方法顯示字串流裡面的內容
ostringstream format_message;
format_message << "name: " << "張飛" << "\n"
<< "age: " << 22 << "\n" << endl;
cout << format_message.str() << endl;
string dump; // 用於丟掉資料
string name;
int age;
istringstream input_istring (format_message.str());
input_istring >> dump;
input_istring >> name;
input_istring >> dump;
input_istring >> age;
cout << "result" << endl;
cout << name << endl;
cout << age << endl;
return 0;
}
result
hello world!
name: 張飛
age: 22
result
張飛
22