是否有任何std :: istream操纵器从输入中使用预定义的字符串?

时间:2014-02-06 09:34:16

标签: c++ boost iostream

我有这样的字符串:

some text that i'd like to ignore 123 the rest of line

格式是固定的,只有数字会发生变化。我想阅读这个“123”并忽略其余部分,但要验证其余部分是否采用假定的格式。如果我使用scanf,我可以写:

int result = scanf("some text that i'd like to ignore %d the rest of line", &number);
assert(result==1);

然后通过检查结果我会知道该行的格式是否正确。我正在寻找一些std ::或boost ::方法,例如使用这样的修饰符:

std::cin >> std::check_input("some text that i'd like to ignore") >> number >> std::ws >> std::check_input("the rest of line");
assert(!std::cin.fail());

当然我可以自己编写,但我不能相信没有简单的方法只使用std或boost来做到这一点。

有吗?

编辑:在这种情况下,正则表达式对我来说太过分了。

1 个答案:

答案 0 :(得分:8)

使用Boost,您可以使用Spirit的qi::match操纵器:

std::istringstream input("some text that i'd like to ignore 42 \tthe rest of line");

int number;

if (input >> std::noskipws >> qi::phrase_match(
         "some text that i'd like to ignore" 
      >> qi::int_ 
      >> "the rest of line", qi::space, number))
{
    std::cout << "Successfully parsed (" << number << ")\n";
}

打印

Successfully parsed (42)

查看 Live On Coliru

当然,Boost Spirit 比这更强大更强大,但是......它也可以用于这样的快速解决方案!

完整样本

为后代保留的代码:

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_match.hpp>
#include <iostream>
#include <sstream>

namespace qi = boost::spirit::qi;

int main()
{
    std::istringstream input("some text that i'd like to ignore 42 \tthe rest of line");

    int number;

    if (input >> std::noskipws >> qi::phrase_match(
             "some text that i'd like to ignore" 
          >> qi::int_ 
          >> "the rest of line", qi::space, number))
    {
        std::cout << "Successfully parsed (" << number << ")\n";
    }

}