【day0411 C++】字符串流istringstream和ostringstream的用法

来源:互联网 发布:道教地狱知乎 编辑:程序博客网 时间:2024/05/22 03:32

# C++对于字符串引入了ostringstream、istringstream、stringstream三个类,

   使用时需要包含<sstream>这个头文件。


* istringstream类:用于执行C++风格的串流的输入操作。
* ostringstream类:用于执行C风格的串流的输出操作。
* strstream类:同时可以支持C风格的串流的输入输出操作。
* istringstream的构造函数原形:istringstream::istringstream(string str);

  .它的作用是从string对象str中读取字符。

# 字符串流存放在内存里,操作速度快。

Demo:

#include <iostream>#include <sstream>  //字符串流/*字符串流在内存里,速度快*/using namespace std;int main(){    cout << "将数据输入到字符串流...\n";    ostringstream osstream;    osstream << "姓名: " << "douBi" << "\n" //必须加空格来区分字符串,这里在'姓名'后了加空格             << "年龄: " << 22 << "\n"             << "体重: " << 88.8 << "\n";    cout << "将内存中的字符流读出:\n" << osstream.str();    cout << endl << "读取内存中的字符流:" << endl;    string dump;   //丢弃的数据    string name;    int age;    double weight;    istringstream isstream(osstream.str());    isstream >> dump;  //丢弃 姓名    cout << "dump: " << dump << endl;    isstream >> name;    isstream >> dump;    cout << "dump: " << dump << endl;    isstream >> age;    isstream >> dump;    cout << "dump: " << dump << endl;    isstream >> weight;    cout << name << endl;    cout << age  << endl;    cout << weight << endl;    return 0;}
输出:



0 0
原创粉丝点击