1.字符串转数字函数
字符串转数字是编程中常见的需求,自己手写这个需求倒不是很难,但是如果有直接可以调用的库则是十分便捷的。为此,C++标准库提供了一系列的字符串转数字 的函数。常用的如下:
1.1stoi()
函数
- 这里的
stoi
意思即是string to int
,简写下来就是stoi()
函数。 - 简单示例
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int main(){
string a = "2";
int a1 = stoi(a);
cout << "a1 = "<< a1 <<"\n";
}
- 执行结果
1.2 stod()
函数
-
string to double
- 简单示例
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int main(){
string b = "2.3";
double b1 = stod(b);
cout << "b1 = "<< b1 << "\n";
}
- 执行结果