您的位置:首页 > 编程语言 > C语言/C++

[转]c++标准库sstream的用法

2020-05-08 04:13 1071 查看

<sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本。注意,<sstream>使用string对象来代替字符数组。这样可以避免缓冲区溢出的危险。而且,传入参数和目标对象的类型被自动推导出来,即使使用了不正确的格式化符也没有危险。

istringstream的用法

 

 
  1.  
    #include <string> // std::string
  2.  
    #include <iostream> // std::cout
  3.  
    #include <sstream> // std::istringstream
  4.   
  5.  
    int main () {
  6.  
    std::istringstream iss;
  7.  
    std::string strvalues = "32 240 2 1450";
  8.   
  9.  
    iss.str (strvalues);
  10.   
  11.  
    for (int n=0; n<4; n++)
  12.  
    {
  13.  
    int val;
  14.  
    iss >> val;
  15.  
    std::cout << val << '\n';
  16.  
    }
  17.  
    std::cout << "Finished writing the numbers in: ";
  18.  
    std::cout << iss.str() << '\n';
  19.  
    return 0;
 

stringstream的用法

  

  1.  
    // swapping ostringstream objects
  2.  
    #include <string> // std::string
  3.  
    #include <iostream> // std::cout
  4.  
    #include <sstream> // std::stringstream
  5.   
  6.  
    int main () {
  7.   
  8.  
    std::stringstream ss;
  9.   
  10.  
    ss << 100 << ' ' << 200;
  11.   
  12.  
    int foo,bar;
  13.  
    ss >> foo >> bar;
  14.   
  15.  
    std::cout << "foo: " << foo << '\n';
  16.  
    std::cout << "bar: " << bar << '\n';
  17.   
  18.  
    return 0;
  19.  
    }
 
leetcode上有一道题目,利用stringstream可以很好地解决:leetcode

 

 
  1.  
    class Solution {
  2.  
    public:
  3.  
    int countSegments(string s) {
  4.  
    stringstream input(s);
  5.  
    int count = 0;
  6.  
    string temp;
  7.  
    while (input>>temp)
  8.  
    {
  9.  
    count++;
  10.  
    }
  11.  
    return count;
  12.  
    }
  13.  
    };
 

 

 


---------------------
作者:svdalv
来源:CSDN
原文:https://blog.csdn.net/ns708865818/article/details/53557957
版权声明:本文为作者原创文章,转载请附上博文链接!

Shawn Chou 原创文章 0获赞 2访问量 1万+ 关注 私信
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: