C++中使用sstream进行类型转换(数字字符串转数字、数字转数字字符串)

1、sstream知识

  • sstream即字符串流。在使用字符串流sstream时,需要先引入相应的头文件 “#include
  • 基本操作
// 引入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;
}

运行截图

猜你喜欢

转载自www.cnblogs.com/komean/p/11112722.html
今日推荐