c++字符串转换为数字(stoi, stol, stoul, stoull, stof, stod, stold)

头文件#include <string>

1. stoi

将字符串转换成int

1
2
int stoi (const string&  str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);

base是指string里的数字是几进制的。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <bits/stdc++.h>
using namespace std;

int main(){
string str_bin = "1010";
string str_hex = "a";
string str_auto = "0x3f3f3f3f";
string str_dec = "12345";
string str_oct = "10";
cout << str_bin << " " << stoi(str_bin, nullptr, 2) << "\n";
cout << str_hex << " " << stoi(str_hex, nullptr, 16) << "\n";
cout << str_auto << " " << stoi(str_auto, nullptr, 0) << "\n";
cout << str_dec << " " << stoi(str_dec, nullptr, 10) << "\n";
cout << str_oct << " " << stoi(str_oct, nullptr, 8) << "\n";
return 0;
}

2. stol

将字符串转化为long

3. stoul

将字符串转化为unsigned long

4. stoll

将字符串转化为long long

5. stoull

将字符串转化为unsigned long long

6. stof

将字符串转化为float

7. stod

将字符串转化为double

8. stold

将字符串转化为long double

恰似你一低头的温柔,较弱水莲花不胜寒风的娇羞, 我的心为你悸动不休。  --mingfuyan

千万不要图快——如果没有足够的时间用来实践, 那么学得快, 忘得也快。