1.stoi()、stof()、stod() 实现字符串转 int、float、double。
- stoi -> string to integer
- stof -> string to float
- stod -> string to double
函数原型:
int stoi (const string& str, size_t* idx = 0, int base = 10); //ids: 指明从字符串何处开始转,base: 转换成几进制数
float stof (const string& str, size_t* idx = 0); //ids: 指明从字符串何处开始转(默认从字符串首字母开始)
double stod (const string& str, size_t* idx = 0); //ids: 指明从字符串何处开始转(默认从字符串首字母开始)
1 #include<iostream>
2 using namespace std;
3
4 int main() {
5 string s = "3.14"; //数字字符串
6 int i = stoi(s); //字符串转整型
7 float f = stof(s); //字符串转浮点型
8 double d = stod(s); //字符串转双精度浮点型
9 cout << i << " " << f << " " << d << endl;
10 return 0;
11 }
notes: 字符串中如果含有非数字的字符,则会抛出异常。如果非数字字符在数字字符之后,会自动截取前面的数字字符!
1 #include<iostream>
2 using namespace std;
3
4 int main() {
5 string s = "abc3.14"; //非法数字字符串
6 int i = stoi(s); //字符串转整型
7 float f = stof(s); //字符串转浮点型
8 double d = stod(s); //字符串转双精度浮点型
9 cout << i << " " << f << " " << d << endl;
10 return 0;
11 }
Error: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion
#include<iostream>
using namespace std;
int main() {
string s = "3.14abd#"; //数字字符串,只会截取3.14,abc会抛弃掉!
int i = stoi(s); //字符串转整型
float f = stof(s); //字符串转浮点型
double d = stod(s); //字符串转双精度浮点型
cout << i << " " << f << " " << d << endl;
return 0;
}
Output: 3 3.14 3.14
2. 数字转字符串 -- to_string() and stringstream
方法一:通过 to_string(value) 方法
1 int main() {
2 double PI = 3.1415926;
3 string p = "PI is " + to_string(PI);
4 cout << p << endl;
5 return 0;
6 }
方法二:通过 stringstream 字符流操作
1 #include<iostream>
2 #include <sstream>
3 using namespace std;
4
5 int main() {
6 double PI = 3.1415926;
7 stringstream ss; // 声明一个字符流对象
8 string p;
9 ss << PI; // 将double型数据输入流中
10 ss >> p; // 将流中数据输出到字符串中
11 cout << "PI is " << p << endl;
12 return 0;
13 }
来源:https://www.cnblogs.com/sheepcore/p/12371951.html