【问题标题】:C++ Adapting sscanf code to istringstream with error checkingC++ 使用错误检查使 sscanf 代码适应 istringstream
【发布时间】:2014-01-21 04:17:22
【问题描述】:

所以我有一些代码可以使用 sscanf 将字符串拆分为其他变量,如下所示。

if(sscanf(input_line.c_str(), "%s %s %lf %lf %lf", &string1, &string2, &point1, &point2, &point3) != 5) {
    //does stuff
    throw;
}

我使用 sscanf 的返回值来验证输入字符串。

我会用

istringstream ss(input_line);
ss >> string1 >> string2 >> point1 >> point2 >> point3;
if( ??????? ){
    //does stuff
    throw;
}

但我不知道如何验证是否正好填充了 5 个东西。我很想摆脱遗留的 C 代码,因为我讨厌 char 数组,但我不想丢失错误检查。我非常感谢任何建议来调整此 istringstream 代码或使用完全不同的 c++ 样式代码来摆脱 char 数组但保留现有功能。

提前致谢,

最大

【问题讨论】:

    标签: c++ scanf istringstream error-checking


    【解决方案1】:

    首先要记住所有输入运算符函数(>>)都返回输入流,其次要记住一个流可以用作booleancondition

    这意味着你可以做例如

    std::string string1, string2;
    double point1, point2, point3;
    
    if (some_input_stream >> string1 >> string2 >> point1 >> point2 >> point3)
    {
        // All is okay
    }
    else
    {
        // One of the input operations failed
    }
    

    要确切知道哪个输入操作失败,您可以一次执行一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 2012-02-17
      • 1970-01-01
      • 2012-03-02
      • 2018-07-02
      • 2019-04-28
      • 2011-02-15
      相关资源
      最近更新 更多