溫馨提示×

如何結合C++異常處理機制使用strtoul

c++
小樊
137
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女