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

时间:2019-04-11 02:56:11

标签: c++ string stringstream

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

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

仅使用std::stringstreamstd::string的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

是的,您只能使用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

答案 1 :(得分: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

相关问题