21xrx.com
2025-03-27 23:22:52 Thursday
文章检索 我的文章 写文章
C++字符串转数字
2023-07-07 12:54:16 深夜i     16     0
C++ string 字符串 转换 数字

C++是一种强大的编程语言,它提供了许多有用的功能和工具。其中,字符串转数字是一个常见的需求,本文将为大家介绍C++中字符串转数字的方法。

C++中可以使用stoi(字符串转整数)、stod(字符串转双精度浮点数)、stof(字符串转单精度浮点数)和stol(字符串转长整型)等函数来完成字符串转数字的操作。这些函数均为C++11标准引入的,它们都接受一个字符串作为参数,将其转化为相应的数字类型并返回。

以stoi函数为例,其使用方式如下:

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

在上述代码中,我们将字符串“123”作为参数传递给stoi函数,结果返回一个整型数字123。同样地,stod函数和stof函数可以用于将字符串转化为浮点数。

需要注意的是,如果字符串中包含非数字字符,以上函数将抛出异常。因此,在使用stoi等函数进行字符串转数字时,一定要确保字符串中只包含数字字符。

除了以上函数外,我们还可以使用stringstream类完成字符串转数字的操作。stringstream类是C++标准库中的类之一,它可以将任意类型的数据转换成字符串,也可以将字符串转换成任意类型的数据,包括数字类型。以下是使用stringstream类完成字符串转数字的示例代码。

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

在以上代码中,我们首先将字符串“123”通过stringstream类的<<运算符转换为一个流对象,然后再通过>>运算符将流对象中的数字转换为整型并赋值给变量num。

综上所述,C++提供了多种方法用于将字符串转换为数字,其中包括了stoi、stof、stod、stol和stringstream等函数和类。在实际编程中,我们可以根据需求和实际情况选择不同的方法来完成字符串转数字的操作。

  
  

评论区

请求出错了