21xrx.com
2025-03-29 09:59:15 Saturday
文章检索 我的文章 写文章
C++ 教程:如何提取字符串中的数字
2023-07-05 02:40:46 深夜i     20     0
C++ 字符串 数字 提取 教程

C++作为一门高性能的编程语言,在数字处理方面具有很高的效率和可靠性。提取字符串中的数字在很多实际应用中都是必要的操作,比如说解析网络数据包中的数字、提取文本中的规律性信息等等。本教程旨在介绍如何使用C++提取字符串中的数字。

首先,我们需要头文件` `和` `。` `头文件中的`stringstream`类可以方便的实现字符串流的读取和写入,而` `头文件中的`string`类提供了对字符串的常见操作方法。

接下来,我们可以使用`stringstream`类的`<<`操作符对字符串进行读取:

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

上述代码中,我们定义了一个字符串变量`str`,其中包含了多个数字。然后,我们使用`stringstream`类的构造函数`stringstream ss(str)`来将字符串转化成数字流。定义一个整型变量`num`,并使用`while`循环来读取数字流中的数字。循环结束后,我们可以输出所有提取的数字。

当然,实际应用中可能需要提取的数字类型不仅限于整型。在这种情况下,我们可以使用`stringstream`类的`str()`方法将数字流转化为字符串,再使用`stod()`和`stof()`等函数将其转化为其他类型:

#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main() {
  string str = "hello 123.456 world 789.123";
  stringstream ss(str);
  double num1, num2;
  while(ss >> str) {
    try {
      num1 = stod(str);
      cout << "double: " << num1 << endl;
    } catch (...)
      continue;
    
    try {
      num2 = stof(str);
      cout << "float: " << num2 << endl;
    } catch (...)
      continue;
    
  }
  return 0;
}

上述代码中,我们定义了一个字符串变量`str`,其中包含了多个浮点数。然后,我们使用`stringstream`类的构造函数`stringstream ss(str)`来将字符串转化成数字流。定义两个浮点数变量`num1`和`num2`,并使用`while`循环来读取数字流中的每一个字符串。将每个字符串尝试转化为浮点数类型,并使用`stod()`和`stof()`函数将其转化为双精度浮点数和单精度浮点数类型。由于在字符串中存在非数字字符,所以必须用`try`和`catch`语句来处理转换异常。

总的来说,使用C++提取字符串中的数字可以极大地方便开发者的工作,因此,我们可以使用此方法来方便地完成各类数字提取工作。

  
  

评论区

请求出错了