c++

如何结合C++异常处理机制使用strtoul

小樊
84
2024-08-30 02:57:29
栏目: 编程语言

strtoul 函数是一个 C 语言库函数,用于将字符串转换为无符号长整数

以下是一个示例,展示了如何在 C++ 中使用 std::strtoul 和异常处理:

#include<iostream>
#include <cstdlib>
#include <stdexcept>
#include<limits>

unsigned long convertStringToUnsignedLong(const std::string& str) {
    char* end;
    unsigned long result = std::strtoul(str.c_str(), &end, 10);

    if (end == str.c_str()) {
        throw std::invalid_argument("The input string is not a valid number.");
    }

    if (*end != '\0') {
        throw std::invalid_argument("The input string contains invalid characters.");
    }

    if (result == ULONG_MAX && errno == ERANGE) {
        throw std::out_of_range("The input number is out of range for an unsigned long.");
    }

    return result;
}

int main() {
    try {
        std::string input = "12345";
        unsigned long number = convertStringToUnsignedLong(input);
        std::cout << "The converted number is: "<< number<< std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what()<< std::endl;
    }

    return 0;
}

在这个示例中,我们定义了一个名为 convertStringToUnsignedLong 的函数,该函数接受一个字符串参数并返回一个无符号长整数。我们使用 std::strtoul 来执行转换,并根据转换过程中可能发生的错误情况抛出相应的异常。在 main 函数中,我们使用 try-catch 块来捕获并处理可能的异常。

0
看了该问题的人还看了