21xrx.com
2024-09-20 00:55:32 Friday
登录
文章检索 我的文章 写文章
C++字串转数字函数
2023-06-30 07:03:19 深夜i     --     --
C++ 字符串 转换 数字函数 数据类型

C++是一门广泛应用的高级编程语言,在日常编程中,我们经常需要将字符类型的数据转化为数字类型的数据。这一过程在C++中需要使用到字符串转数字的函数,下面就让我们来认识一下关于C++字串转数字函数。

C++中提供了多个函数可以实现字串转数字,最常用的是atoi()函数、atof()函数、stoi()函数、stof()函数和stod()函数。这些函数的具体用法如下:

1. atoi()函数:将字符串转化为整数类型的函数。


#include <cstdlib>

int atoi (const char* str);

2. atof()函数:将字符串转化为双精度浮点类型的函数。


#include <cstdlib>

double atof (const char* str);

3. stoi()函数:将字符串转化为整数类型的函数,功能与atoi()函数类似。


#include <string>

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

其中,str表示待转字符串,base表示进制(如:十进制,十六进制等),idx表示转换后不偏移的位置指针。

4. stof()函数:将字符串转化为浮点类型的函数。


#include <string>

float stof (const string& str, size_t* idx = 0);

5. stod()函数:将字符串转化为双精度浮点类型的函数,功能与atof()函数类似。


#include <string>

double stod (const string& str, size_t* idx = 0);

举个例子,下面是使用stoi()函数将字串转数字的示例代码:


#include <iostream>

#include <string>

using namespace std;

int main() {

 string s = "100";

 int i = stoi(s);

 cout << i << endl;

 return 0;

}

在这个例子中,我们先定义了一个字符串s,其中存储了待转换的字串“100”。接着,我们调用了stoi()函数,将s这个字符串转换成整数类型,并将其存储到整数变量i中。最后,我们通过cout输出i的值,结果就是100。

总的来说,无论是atoi()函数、atof()函数、stoi()函数、stof()函数还是stod()函数,它们都是C++中实现字串转数字的常用函数,使用起来也非常有便利性。因此,了解和掌握这些函数的使用,对于C++编程的学习和实践都是非常重要的。

  
  

评论区

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