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;
}
運行截圖

