zoukankan      html  css  js  c++  java
  • stringsream用法

    stringstream:

    头文件:

    #include <sstream>

    简单整理一下这玩意的作用,主要有三个吧.

    • 类型转化
    • 字符串拼接
    • 字符串整合(这一个用处特别大!!!!!!!)

     先插个话,赋值语句:(这是个 流 的东西其实也不能叫赋值语句)

    1 string  str;
    2     stringstream ss;
    3     str = "123.456789";  
    4     ss << str;
    5 
    6 
    7 //和stringstream ss(str); 是一样的

    一.类型转化

    1.字符串转数字

     1     double  dVal;    
     2     int     iVal;
     3     string  str;
     4     stringstream ss;
     5     
     6     // string -> double
     7     str = "123.456789";  
     8     ss << str;
     9     ss >> dVal;
    10     cout << "dVal: " << dVal << endl;
    11  
    12     // string -> int
    13     str = "654321";  
    14     ss.clear();//一定别忘记清空!
    15     ss << str;
    16     ss >> iVal;
    17     cout << "iVal: " << iVal << endl;  
    18         
    19     return 0;  

    2.数字转字符串

    1 void i2s(int num,string &str){
    2 stringstream ss;
    3 ss<<num;
    4 ss>>str;
    5 }

    注意一个问题,要进行多次转换的时候,要对原来那个进行清空

    .clear()  或者 .str(" ");

    (刚刚have a try,发现还是第一个比较好用)

     二.字符串拼接(其实这个功能,放string里+一下就行了)

     1 int main()
     2 {
     3     stringstream sstream;
     4  
     5     // 将多个字符串放入 sstream 中
     6     sstream << "first" << " " << "string,";
     7     sstream << " second string";
     8     cout << "strResult is: " << sstream.str() << endl;
     9  
    10     // 清空 sstream
    11     sstream.str("");
    12     sstream << "third string";
    13     cout << "After clear, strResult is: " << sstream.str() << endl;

    //sstream.str()可以导出在sstream中的所有东西

    三.分割
    这里不得不提一个叫getline 的东西,这个东西默认是不会读到空格停止的.看这个吧:https://www.cnblogs.com/zhmlzhml/p/12669967.html
    getline不会因空格而停止(一读读一行)但是输入输出流会(包括伟大的cin),两者配合,可以成功实现单词的分割
    #include<sstream>
    #include<iostream>
    using namespace std;
    int main()
    {
            string line,word;
            while(getline(cin,line))
            {
                    stringstream stream(line);
                    cout<<stream.str()<<endl;
                    while(stream>>word){cout<<word<<endl;}//挨个出去
            }
            return 0;
    }
     
     
     
  • 相关阅读:
    极速地将git项目部署到SAE的svn服务器上
    深入了解Javascript模块化编程
    自己实现的一款在线Javascript正则表达式测试器——JRE-Parser
    Javascript中的一种深复制实现
    如何循序渐进地学习Javascript
    handsontable实例----来源github
    HandsontableWithVue (一) 导入官方的汉化包
    Handsontable 入坑的开始
    开始前端的生活
    c3p0数据源的第一次尝试
  • 原文地址:https://www.cnblogs.com/zhmlzhml/p/12465566.html
Copyright © 2011-2022 走看看