C++_数字字符串互相转换

数字转换为字符串

法一、利用<sstream>中的stringstream(字符串流)

 1 int main(){
 2 
 3     int x;
 4     string res;
 5     stringstream ss;
 6     cin>>x; ss<<x; ss>>res;
 7     cout<<res<<endl;
 8 
 9     return 0;
10 }

法二、利用<sstream>中的to_string,最好用于int,浮点数有些特殊

 1 int main(){
 2 
 3     double x;
 4     string res;
 5     stringstream ss;
 6     cin>>x; 
 7     res = to_string(x);
 8     cout<<res<<endl;
 9 
10     return 0;
11 }

输出

123.123
123.123000

浮点数会保存小数点后六位,不足补零。

将字符串转为数字

法一、利用<string>中的 stoi()、stof()、stod()函数,可将字符串分别转换为整型、单精度浮点型、双精度浮点型

1 int main(){
2 
3     string res = "123";
4     int x = stoi(res);
5     cout<<x<<endl;
6     return 0;
7 }

法二、利用<sstream>中的stringstream(字符串流)

当然上面两种抓换也可通过sprintf、sscanf实现

原文地址:https://www.cnblogs.com/fresh-coder/p/14332353.html