我有一个项目,其中输入是特定格式,需要从中提取数据。
格式类似于H79.03 = J99.30
,我需要得到浮点数。
如何仅使用std::stringstream
和std::string
来实现这一目标的最佳方法是什么?
是的,你只能使用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
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...
}