Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++string转int

作者:硝烟   发布日期:2025-07-06   浏览:97

#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;
}

解释说明:

  1. 包含头文件#include <iostream> 用于输入输出操作,#include <string> 用于处理 std::string#include <cstdlib> 用于 std::atoi#include <stdexcept> 用于捕获异常。
  2. 函数定义stringToInt 函数接收一个 std::string 类型的参数,并尝试将其转换为整数。使用 std::stoi 进行转换,并捕获可能的异常。
  3. 异常处理:如果输入的字符串不是有效的整数格式(如包含非数字字符),会抛出 std::invalid_argument 异常;如果数字超出 int 的范围,则会抛出 std::out_of_range 异常。
  4. 主函数:在 main 函数中,定义一个字符串 input 并调用 stringToInt 函数进行转换。如果转换成功,输出结果;否则捕获并处理异常。

这个示例展示了如何安全地将 std::string 转换为 int,并处理可能的错误情况。

上一篇:c++ 字符串转数字

下一篇:c++ 析构函数

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站