#include <iostream>
#include <string>
#include <cstdlib> // for atoi
#include <sstream> // for stringstream
int main() {
// 方法1: 使用 atoi 函数
std::string str1 = "12345";
int num1 = atoi(str1.c_str());
std::cout << "Using atoi: " << num1 << std::endl;
// 方法2: 使用 stringstream
std::string str2 = "67890";
std::stringstream ss;
ss << str2;
int num2 = 0;
ss >> num2;
std::cout << "Using stringstream: " << num2 << std::endl;
// 方法3: 使用 stoi 函数 (C++11 及以上)
std::string str3 = "54321";
int num3 = std::stoi(str3);
std::cout << "Using stoi: " << num3 << std::endl;
return 0;
}
使用 atoi 函数:atoi 是 C 标准库中的函数,可以将字符串转换为整数。需要注意的是,如果字符串包含非数字字符,atoi 会在遇到第一个非数字字符时停止转换,并返回已解析的部分结果。
使用 stringstream:stringstream 是 C++ 标准库中的一种流类,可以方便地将字符串转换为其他类型的数据。通过将字符串插入到 stringstream 中,然后提取出整数值。
使用 stoi 函数:stoi 是 C++11 引入的函数,专门用于将字符串转换为整数。它会抛出异常(如 std::invalid_argument 或 std::out_of_range),因此在使用时可以捕获异常来处理错误情况。
上一篇:c++map
下一篇:c++随机数生成
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站