C++字符串流值提取

C++ stringstream value extraction

本文关键字:提取 字符串 C++      更新时间:2023-10-16

我正在尝试使用如下所示std::stringstreammyString1中提取值:

// Example program
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
  string myString1 = "+50years";
  string myString2 = "+50years-4months+3weeks+5minutes";
  stringstream ss (myString1);
  char mathOperator;
  int value;
  string timeUnit;
  ss >> mathOperator >> value >> timeUnit;
  cout << "mathOperator: " << mathOperator << endl;
  cout << "value: " << value << endl;
  cout << "timeUnit: " << timeUnit << endl;
}

输出:

mathOperator: +
value: 50
timeUnit: years

在输出中,您可以看到我成功提取了我需要的值、数学运算符、值和时间单位。

有没有办法对myString2做同样的事情?也许在循环中?我可以提取数学运算符,值,但时间单位只是提取其他所有内容,我想不出解决这个问题的方法。非常感谢。

问题是 timeUnit 是一个字符串,所以>>会提取任何内容,直到第一个空格,而你的字符串中没有。

选择:

  • 您可以使用 getline() 提取部分,它会提取字符串,直到找到分隔符。 不幸的是,您没有一个潜在的分隔符,而是 2(+ 和 -)。
  • 您可以选择直接在字符串上使用正则表达式
  • 您最终可以使用 find_first_of()substr() 拆分字符串。

作为说明,这里是正则表达式的示例:

  regex rg("([\+-][0-9]+[A-Za-z]+)", regex::extended);
  smatch sm;
  while (regex_search(myString2, sm, rg)) {
      cout <<"Found:"<<sm[0]<<endl;
      myString2 = sm.suffix().str(); 
      //... process sstring sm[0]
  }

这是一个现场演示,应用您的代码来提取所有元素。

你可以

像下面的例子一样更健壮<regex>

#include <iostream>
#include <regex>
#include <string>
int main () {
  std::regex e ("(\+|\-)((\d)+)(years|months|weeks|minutes|seconds)");
  std::string str("+50years-4months+3weeks+5minutes");
  std::sregex_iterator next(str.begin(), str.end(), e);
  std::sregex_iterator end;
  while (next != end) {
    std::smatch match = *next;
    std::cout << "Expression: " << match.str() << "n";
    std::cout << "  mathOperator : " << match[1] << std::endl;
    std::cout << "  value        : " << match[2] << std::endl;
    std::cout << "  timeUnit     : " << match[4] << std::endl;
    ++next;
  }
}

输出:

Expression: +50years
  mathOperator : +
  value        : 50
  timeUnit     : years
Expression: -4months
  mathOperator : -
  value        : 4
  timeUnit     : months
Expression: +3weeks
  mathOperator : +
  value        : 3
  timeUnit     : weeks
Expression: +5minutes
  mathOperator : +
  value        : 5
  timeUnit     : minutes

现场演示

我会使用

getline 作为timeUnit,但由于getline只能使用一个分隔符,我将单独搜索字符串以查找mathOperator并使用它:

string myString2 = "+50years-4months+3weeks+5minutes";
stringstream ss (myString2);
size_t pos=0;
ss >> mathOperator;
do
  {
    cout << "mathOperator: " << mathOperator << endl;
    ss >> value;
    cout << "value: " << value << endl;
    pos = myString2.find_first_of("+-", pos+1);
    mathOperator = myString2[pos];
    getline(ss, timeUnit, mathOperator);
    cout << "timeUnit: " << timeUnit << endl;
  }
while(pos!=string::npos);