std::string 类型转换为 UINT(即 unsigned int)类型

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,则表示转换结果超出范围。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云缘若仙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值