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