zoukankan      html  css  js  c++  java
  • C++中使用sstream进行类型转换(数字字符串转数字、数字转数字字符串)

    1、sstream知识

    • sstream即字符串流。在使用字符串流sstream时,需要先引入相应的头文件 “#include <sstream>”
    • 基本操作
    // 引入sstream头文件
    #include <sstream>
    // 定义字符串流
    stringstream ss;
    

    类型转换过程

    // 字符转数字
    ss << string("15");
    int num;
    ss >> num;
    
    // 如果多次使用ss进行转换,需使用clear()函数对内容清空
    ss.clear();
    
    // 数字转字符
    ss << 67;
    string str;
    ss >> str;
    

    2、测试

    #include <iostream>
    #include <sstream>
    using namespace std;
    
    /* 数字字符串转数字 */
    void str2Num(string str){
        // 定义中间转换变量stringstream
        stringstream ss;
        // 定义整型变量
        int num;    
        // 转换过程
        ss << str;
        ss >> num;
        // 打印结果
        cout << num << endl;  
    }
    
    /* 数字转数字字符串 */
    void num2Str(int num){
        // 定义中间转换变量stringstream
        stringstream ss;
        // 定义字符串变量
        string str;
        // 转换过程
        ss << num;
        ss >> str;
        // 打印结果
        cout << str << endl;
    }
    
    
    int main()
    {    
        string str = string("35");         
        str2Num(str);
        int num = 15;
        num2Str(num);
    
        return 0;
    }
    
    

    运行截图

  • 相关阅读:
    2021年4月27日 团队冲刺阶段01
    2021年4月26日
    2021年4月25日
    2021年4月24日
    2021年4月23日
    2021年4月22日
    2021年4月21日
    神奇的数列之“Last Defence ”
    经典圆交面积求解之“Intersection ”
    计蒜客第六场
  • 原文地址:https://www.cnblogs.com/komean/p/11112722.html
Copyright © 2011-2022 走看看