zoukankan      html  css  js  c++  java
  • stringstream的基本用法

    stringstream是字符串流。它将流与存储在内存中的string对象绑定起来。

    在多种数据类型之间实现自动格式化。

    1 stringstream对象的使用

     1 #include <sstream>
     2 #include <iostream>
     3 using namespace std;
     4 int main()
     5 {
     6     string line,word;
     7     while(getline(cin,line))  //从屏幕输入字符串
     8     {
     9         stringstream stream(line);//定义了一个字符串流
    10         cout<<stream.str()<<endl;
    11         while(stream>>word)  
    12         {
    13             cout<<word<<endl;
    14         }
    15     }
    16     return 0;
    17 }
    stringstream使用代码示例

    输入:shanghai no1 school 1989

    输出:shanghi no1 school 1989

          shanghai

        no1

        school

        1989

    2stringstream提供的转换和格式化

     1 #include <sstream>
     2 #include <iostream>
     3 using namespace std;
     4 int main()
     5 {
     6     int val1 = 512,val2 = 1024;
     7     stringstream ss;
     8 
     9     //将int类型读入ss,变为string类型
    10     ss<<"val1: "<<val1<<endl //"vall:"此处有空格,字符串流是通过空格判断一个字符串的结束
    11       <<"val2: "<<val2<<endl;
    12     cout<<ss.str();
    13     string dump;
    14     int a,b;
    15 
    16     //提取512,1024保存为int类型。当然,如果a,b声明为string类型
    17     //那么这两个字面值常量相应保存为string类型
    18     ss>>dump>>a>>dump>>b;
    19     cout<<a<<" "<<b<<endl;
    20     return 0;
    21 }
    View Code

    输出为:val1: 512

        val2: 1024

        512 1024

    3其他注意

      stringstream不会主动释放内存(或许是为了提高效率),但如果你要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消 耗,因些这时候,需要适时地清除一下缓冲 (用 stream.str("") )

    #include <cstdlib>
    #include <sstream>
    #include <iostream>
    using namespace std;
    int main()
    {
        stringstream ss;
        
        string s;
        ss<<"shanghai no1 school";
        ss>>s;
        cout<<"size of stream= "<<ss.str().length()<<endl;
        cout<<"s: "<<s<<endl;
        ss.str("");
        cout<<"size of stream= "<<ss.str().length()<<endl;
        return 0;
    }
    View Code

    输出:

    size of stream = 19

    s: shanghai

    size of stream = 0

  • 相关阅读:
    [LintCode] Valid Palindrome 验证回文字符串
    [LeetCode] 378. Kth Smallest Element in a Sorted Matrix 有序矩阵中第K小的元素
    [LintCode] Integer to Roman 整数转化成罗马数字
    [LintCode] Roman to Integer 罗马数字转化成整数
    [LintCode] Scramble String 爬行字符串
    [LintCode] Count and Say 计数和读法
    [LintCode] Simplify Path 简化路径
    [LintCode] Length of Last Word 求末尾单词的长度
    [LintCode] Valid Parentheses 验证括号
    [LeetCode] 377. Combination Sum IV 组合之和之四
  • 原文地址:https://www.cnblogs.com/baoxiaofei/p/4295931.html
Copyright © 2011-2022 走看看