21xrx.com
2025-03-24 10:43:11 Monday
文章检索 我的文章 写文章
C++中string类型转换为int类型的方法
2023-06-23 05:19:14 深夜i     46     0
C++ string类型 int类型 转换方法 字符串转整数

C++中,我们经常需要将string类型转换为int类型,例如从文件中读取数据时,将读取到的字符串转换为整数类型进行处理。下面介绍两种将string类型转换为int类型的方法。

方法一:使用标准库函数stoi()

C++11标准库提供了stoi()函数,可以将string类型转换为int类型。该函数定义在 头文件中,其语法格式如下:

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

其中,str表示待转换的字符串,idx表示存储转换失败后下一个字符的索引(可为空指针),base表示转换的进制(默认为十进制)。

下面是一个简单的示例代码:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str = "1234";
  int num = stoi(str);
  cout << num << endl;
  return 0;
}

输出结果:

1234

方法二:使用stringstream类

另一种将string类型转换为int类型的方法是使用stringstream类。该类定义在 头文件中,可以将字符串按照给定的格式转换为各种数据类型。

下面是一个简单的示例代码:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
  string str = "1234";
  stringstream ss;
  ss << str;
  int num;
  ss >> num;
  cout << num << endl;
  return 0;

输出结果:

1234

总结:

这两种方法都很简单,建议使用C++11标准库提供的stoi()函数,因为它更简洁、直观、安全。如果要转换的字符串格式较为复杂,可以使用stringstream类,其可以实现更为复杂的字符串格式转换。

  
  

评论区