21xrx.com
2024-09-17 03:45:59 Tuesday
登录
文章检索 我的文章 写文章
C++实现string转int
2023-07-11 21:38:36 深夜i     --     --
C++ string 转换 int 实现

在编程中,我们常常需要将字符串转换为整型数据类型,例如在许多算法中需要将用户输入的字符串转换为数字进行计算。在C++中,我们可以通过一些方法实现字符串转int的功能。

最简单的方法是使用C++中的std::stoi函数。std::stoi函数可以将一个字符串转换为int类型的变量。要使用std::stoi函数,我们需要包含头文件 。函数的原型如下:

int stoi (const string& str, size_t* idx = 0, int base = 10);

其中,str是需要转换的字符串,idx是转换结束的位置,base是转换的进制。如果不指定idx和base,则默认为10进制。

下面是一个例子,展示了如何使用std::stoi函数:


#include <iostream>

#include <string>

int main() {

 std::string str = "123";

 int num = std::stoi(str);

 std::cout << "The string is " << str << std::endl;

 std::cout << "The number is " << num << std::endl;

 return 0;

}

输出结果为:


The string is 123

The number is 123

在这个例子中,我们首先将一个字符串"123"赋值给变量str,然后使用std::stoi将其转换为整型变量num。最后输出结果。

除了std::stoi函数外,还可以使用C++11中的std::stringstream来实现字符串转int的功能。stringstream类允许我们将字符串当作输入源或输出目标来使用。它可以像cin和cout一样读写数据。

下面是一个例子,展示了如何使用std::stringstream类:


#include <iostream>

#include <string>

#include <sstream>

int main() {

 std::string str = "456";

 std::stringstream ss(str);

 int num;

 ss >> num;

 std::cout << "The string is " << str << std::endl;

 std::cout << "The number is " << num << std::endl;

 return 0;

}

输出结果为:


The string is 456

The number is 456

在这个例子中,我们首先将一个字符串"456"赋值给变量str,然后使用std::stringstream类将其转换为整型变量num。最后输出结果。

综上所述,C++中实现字符串转int的方法有很多,其中最常用的方法是使用std::stoi函数和std::stringstream类。选择哪种方法主要取决于具体的应用场景。无论使用哪种方法,我们都需要注意字符串的格式和范围,以避免出现无法预料的错误。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复