C++11中string与数值类型的转换

C++中string与数值类型的相互转换记录

string转int、double、long

string s = "123.456";

// string -> int
cout << stoi(s) << endl;
// string -> long
cout << stol(s) << endl;
// string -> float
cout << stof(s) << endl;
// string -> double
cout << stod(s) << endl;

int、double、long、char转string

string s = "Test";
// int -> string
int i = 7;
cout << s + "int:" + to_string(i) << endl;
// float -> string
float f = 3.14;
cout << s + "float:" + to_string(f) << endl;
// double -> string
double d = 3.1415;
cout << s + "double:" + to_string(d) << endl;
// char -> string
char c = 'z';
cout << s + "char_1:" + to_string(c) << endl; // 需注意,这里的c是以ASCII数值传入
cout << s + "char_2:" + c << endl;

综合以上例子,可总结出:

string 转换成 数值类型用:sto+类型开头字母()函数,例如stroi、strol、strod等等

数值类型 转换成 string:用to_string(),需注意**char类型转换成string类型是自动转换,若是用to_string()函数则会将char视为数值ASCII数值传入。

参考文章链接https://blog.csdn.net/HiccupHiccup/article/details/62421032

posted @ 2020-08-26 10:30  凡璞  阅读(218)  评论(0编辑  收藏  举报
1 2
3 4
5 6