将特定格式的字符串拆分为浮点数和字符串

问题描述 投票:0回答:2

我有一个项目,其中输入是特定格式,需要从中提取数据。

格式类似于H79.03 = J99.30,我需要得到浮点数。

如何仅使用std::stringstreamstd::string来实现这一目标的最佳方法是什么?

c++ string stringstream
2个回答
2
投票

是的,你只能使用stringstream和string。首先,用空格替换无效数字。然后取数字。

string originalStr = "H79.03 = J99.30";
string expression = originalStr;
for(int i = 0; i < expression.length(); i++) {
    if (!isdigit(expression[i]) && (expression[i] != '.'))
         expression[i] = ' ';
}
stringstream str(expression);
float firstValue, secondValue;
str >> firstValue;
str >> secondValue;

cout<<firstValue<<endl; // it prints 79.03
cout<<secondValue<<endl; // it prints 99.30

0
投票
std::string s = "H79.03 = J99.30";
std::istringstream iss(s);
double d1, d2;

if (iss.ignore() &&
    iss >> d1 &&
    iss.ignore(4) &&
    iss >> d2)
{
    // is d1 and d2 as needed...
}

Live Demo

© www.soinside.com 2019 - 2024. All rights reserved.