C++字符串和数字相互转化
经常忘记,记录下来
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main(){
string s;
int n;
//方法1,使用stringstream,需包含头文件<sstream>
//字符串->数字 double共保留6位
stringstream ss,sss;
cin >>s;
ss << s;
ss >> n;
cout << typeid(n).name()<<" "<<n<<endl;
double d;
sss << s;
sss >> d;
cout << typeid(d).name()<< " " <<d<<endl;
//数字->字符串
stringstream its,dts;
string is,ds;
its <<n;
dts <<d;
its >>is;
dts >> ds;
cout << is+"/"+ds<<endl;
//方法2,使用stoi,stod,stof等函数,需包含头文件<string>
//字符串->数字
cout << typeid(stoi(s)).name() <<" "<< typeid(stod(s)).name()<<" "<< typeid(stof(s)).name()<<endl;
cout << stoi(s) <<" "<< stod(s)<<" "<<stof(s)<<endl; //double和float共保留6位
//方法3,使用to_string,需包含头文件<sstream>
cout << to_string(n)+"/"+ to_string(d); //保留至小数点后6位
return 0;
}
输入输出。
1234.5678987654
i 1234
d 1234.57
1234/1234.57
i d f
1234 1234.57 1234.57
1234/1234.567899
123456789.87654321
i 123456789
d 1.23457e+08
123456789/1.23457e+08
i d f
123456789 1.23457e+08 1.23457e+08
123456789/123456789.876543