VS2017
#include <iostream>
using std::cout;
using std::endl;
using std::string;
#include <sstream>//stringstream
int main()
{
//方式一:c语言库函数
{
//字符串转换为数字 atoi() atof()
string stra = "527";
string strb = "123.123654";
int numa = atoi(stra.c_str());
double numb = atof(strb.c_str());
cout << "numa = " << numa << endl;//527
cout << "numb = " << numb << endl;//123.124
//数字转换为字符串 itoa() gcvt() 这两个函数被编译器警告
int intV = 212;
double douV = 2018.052721;
char s1[15] = "";
char s2[15] = "";
itoa(intV, s1, 10);
gcvt(douV, 6, s2);
cout << "s1 = " << s1 << endl;//212
cout << "s2 = " << s2 << endl;//2018.05
char s[20] = "";
sprintf(s, "%.3f", douV);//sprintf() 格式化字符串, 被编译器警告
cout << "s = " << s << endl;//2018.053
}
//方式二:stringstream
{
//字符串转化为数字
string s1 = "12", s2 = "3.141592";
int n1 = 0;
double n2 = 0;
std::stringstream ss1, ss2;
ss1 << s1;
ss1 >> n1;
ss2 << s2;
ss2 >> n2;
cout << "n1 = " << n1 << endl;//12
cout << "n2 = " << n2 << endl;//3.14159
//数字转换为字符串
int num1 = 123;
double num2 = 54.123456;
string str1 = "", str2 = "";
std::stringstream tmp1,tmp2;
tmp1 << num1;
tmp1 >> str1;
tmp2 << num2;
tmp2 >> str2;
cout << "str1 = " << str1 << endl;//123
cout << "str2 = " << str2 << endl;//54.1235
}
//方式三:to_string --- stoi stof
{
//数字转换为字符串
int a = 15;
double b = 2.7182818;
cout << "strA = " << std::to_string(a) << endl;//15
cout << "strB = " << std::to_string(b) << endl;//2.718282
//字符串转换为数字
string aa = "1234";
string bb = "512.2625";
int num1 = stoi(aa);
float num2 = stof(bb);
cout << num1 << " " << num2 << endl;//1234 512.263
}
return 0;
}