Sstream using C ++ type conversion (digital-to-digital strings, the digital-to-digital string)

1, sstream knowledge

  • sstream i.e. string stream. When using a string flow sstream, you need to be introduced into the appropriate header files "#include
  • Basic Operations
// 引入sstream头文件
#include <sstream>
// 定义字符串流
stringstream ss;

Type conversion process

// 字符转数字
ss << string("15");
int num;
ss >> num;

// 如果多次使用ss进行转换,需使用clear()函数对内容清空
ss.clear();

// 数字转字符
ss << 67;
string str;
ss >> str;

2, the test

#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;
}

Run shot

Guess you like

Origin www.cnblogs.com/komean/p/11112722.html