【问题标题】:Splitting a string of a specific format to floats and strings将特定格式的字符串拆分为浮点数和字符串
【发布时间】:2019-04-11 02:56:10
【问题描述】:

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

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

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

【问题讨论】:

  • 到目前为止你尝试了什么?发布您的代码。

标签: c++ string stringstream


【解决方案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

【讨论】:

  • 您的循环正在替换浮点数的小数点。不要将它们转换为空格。并且firstValuesecondValue 需要声明为floatdouble 而不是int
  • 感谢@RemyLebeau 的建议。
  • 您仍在丢弃小数点。 isdigit()'.' 返回 false。你需要改用这个:if (!isdigit(expression[i]) &amp;&amp; (expression[i] != '.'))
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多