std::stoul
时间: 2024-02-18 12:02:08 浏览: 19
`std::stoul` 是 C++ 标准库中的一个函数,用于将字符串转换为无符号长整型(unsigned long)。其函数原型如下:
```c++
unsigned long stoul(const string& str, size_t* pos = 0, int base = 10);
```
其中,`str` 表示要转换的字符串;`pos` 表示可选参数,用于返回转换后第一个无法转换的字符位置;`base` 表示可选参数,用于指定进制,默认为 10 进制。
`std::stoul` 函数会尝试将字符串转换为无符号长整型,如果字符串中包含非数字字符,则转换会停止,并返回转换成功的部分。例如:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "12345";
unsigned long num = std::stoul(str);
std::cout << num << std::endl;
str = "12a34";
num = std::stoul(str);
std::cout << num << std::endl; // 输出 12,因为转换停止在 'a' 处
return 0;
}
```
输出结果为:
```
12345
12
```
需要注意的是,`std::stoul` 函数在转换失败时会抛出 `std::invalid_argument` 或 `std::out_of_range` 异常,因此在使用时需要进行异常处理。