istringstream,ostringstream和stringstream

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

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值