1. 使用 std::stoul
函数
std::stoul
是 C++ 标准库中的一个函数,它能够把字符串转换为无符号长整型。要是转换结果能被 UINT
类型容纳,就可将其赋值给 UINT
变量。
#include <iostream>
#include <string>
int main() {
std::string str = "12345";
try {
unsigned int num = static_cast<unsigned int>(std::stoul(str));
std::cout << "转换后的结果: " << num << std::endl;
} catch (const std::invalid_argument& e) {
std::cerr << "无效的字符串: " << e.what() << std::endl;
} catch (const std::out_of_range& e) {
std::cerr << "转换结果超出范围: " << e.what() << std::endl;
}
return 0;
}
代码解释:
std::stoul(str)
会尝试把字符串str
转换为无符号长整型。static_cast<unsigned int>
用于把转换结果强制转换为unsigned int
类型。- 借助
try-catch
块捕获可能出现的异常,例如std::invalid_argument
(字符串格式无效)和std::out_of_range
(转换结果超出范围)。
2. 使用 std::strtoul
函数(C 风格)
std::strtoul
是 C 标准库中的函数,同样可用于将字符串转换为无符号长整型。
#include <iostream>
#include <cstdlib>
#include <string>
int main() {
std::string str = "12345";
char* endptr;
unsigned long num = std::strtoul(str.c_str(), &endptr, 10);
if (*endptr != '\0') {
std::cerr << "无效的字符串" << std::endl;
} else if (num > UINT_MAX) {
std::cerr << "转换结果超出范围" << std::endl;
} else {
unsigned int result = static_cast<unsigned int>(num);
std::cout << "转换后的结果: " << result << std::endl;
}
return 0;
}
代码解释:
str.c_str()
用于把std::string
转换为 C 风格的字符串。std::strtoul
函数会把 C 风格的字符串转换为无符号长整型,endptr
指向第一个不能转换的字符。- 检查
*endptr
是否为'\0'
,若不是则表明字符串格式无效。 - 检查转换结果是否超出
UINT_MAX
,若超出则表明结果超出范围。
3. 使用 std::from_chars
(C++17 及以上)
std::from_chars
是 C++17 引入的一个函数,用于将字符序列转换为数值类型。
#include <iostream>
#include <string>
#include <charconv>
int main() {
std::string str = "12345";
unsigned int num;
auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), num);
if (ec == std::errc()) {
if (ptr == str.data() + str.size()) {
std::cout << "转换后的结果: " << num << std::endl;
} else {
std::cerr << "无效的字符串" << std::endl;
}
} else if (ec == std::errc::result_out_of_range) {
std::cerr << "转换结果超出范围" << std::endl;
} else {
std::cerr << "转换出错" << std::endl;
}
return 0;
}
代码解释:
std::from_chars
尝试把字符串转换为unsigned int
类型,返回一个包含指向未处理字符的指针和错误码的结构体。- 检查错误码
ec
,若为std::errc()
则表示转换成功,接着检查是否所有字符都被处理。 - 若错误码为
std::errc::result_out_of_range
,则表示转换结果超出范围。