21xrx.com
2025-03-25 00:02:33 Tuesday
文章检索 我的文章 写文章
C++字符串转换为整数操作
2023-07-05 19:24:13 深夜i     19     0
C++ 字符串 转换 整数 操作

在C++语言中,字符串和整数之间的转换是一种基本操作,因为需要将一些输入或输出数据格式化成字符串,或者将字符串转换为整数进行计算等操作。这篇文章将介绍C++字符串转换为整数操作的几种方法。

1. 使用stoi函数

C++标准库提供了stoi函数,即字符串转整数,函数的原型如下:

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

其中,str为要转换的字符串,idx是可选的输出参数,用于返回str中第一个非数字字符的位置,base表示进制,缺省为10进制。

使用stoi函数的例子:

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

输出:1234

2. 使用atof函数

C++标准库提供了atof函数,即将字符串转换为浮点数,将浮点数强制转换为整数即可得到整数。函数的原型如下:

double atof (const char* str);

使用atof函数的例子:

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

输出:1234

3. 使用stringstream类

C++标准库提供了stringstream类,可以将字符串转换为各种基本类型。使用stringstream类时,需要包含头文件 。stringstream类的用法如下:

#include <sstream>
#include <string>
using namespace std;
int main()
{
  stringstream ss("1234");
  int a = 0;
  ss >> a;
  cout << a << endl;
  return 0;
}

输出:1234

总结:

通过本文的介绍,我们了解了C++中字符串转换为整数的三种方法:使用stoi函数、使用atof函数和使用stringstream类。在实际的应用中,我们需要综合考虑效率和代码复杂度,选择最合适的方法进行转换。

  
  

评论区