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;
    }
     
     
     
  • 相关阅读:
    .Net core 下Swagger如何隐藏接口的显示
    .Net core 使用SSH.Net上传到SFTP服务器和和下载文件
    centos7 安装mysql5.7以及一些细节问题
    linux安装完jenkins无法访问的问题
    C# 对象的深复制和浅复制
    .Net core 还原Nuget包失败的解决方法
    Vuejs(14)——在v-for中,利用index来对第一项添加class
    Vuejs——(13)组件——杂项
    Vuejs——(12)组件——动态组件
    Vuejs——(11)组件——slot内容分发
  • 原文地址:https://www.cnblogs.com/zhmlzhml/p/12465566.html
Copyright © 2011-2022 走看看