#include <iostream>
#include <string>
#include <cstdlib> // for std::atoi
#include <stdexcept> // for std::invalid_argument
int stringToInt(const std::string& str) {
try {
// 使用 std::stoi 将字符串转换为整数
int result = std::stoi(str);
return result;
} catch (const std::invalid_argument& e) {
// 捕获无效参数异常,例如字符串不是有效的整数格式
std::cerr << "Invalid argument: " << e.what() << '\n';
throw;
} catch (const std::out_of_range& e) {
// 捕获超出范围的异常,例如字符串表示的数字太大或太小
std::cerr << "Out of range: " << e.what() << '\n';
throw;
}
}
int main() {
std::string input = "12345";
try {
int number = stringToInt(input);
std::cout << "Converted integer: " << number << '\n';
} catch (const std::exception& e) {
std::cerr << "Error converting string to integer.\n";
}
return 0;
}
#include <iostream> 用于输入输出操作,#include <string> 用于处理 std::string,#include <cstdlib> 用于 std::atoi,#include <stdexcept> 用于捕获异常。stringToInt 函数接收一个 std::string 类型的参数,并尝试将其转换为整数。使用 std::stoi 进行转换,并捕获可能的异常。std::invalid_argument 异常;如果数字超出 int 的范围,则会抛出 std::out_of_range 异常。main 函数中,定义一个字符串 input 并调用 stringToInt 函数进行转换。如果转换成功,输出结果;否则捕获并处理异常。这个示例展示了如何安全地将 std::string 转换为 int,并处理可能的错误情况。
上一篇:c++ 字符串转数字
下一篇:pytorch c++
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站