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

pep*_*er0 2 c++ boost iostream

我有这样的字符串:

some text that i'd like to ignore 123 the rest of line
Run Code Online (Sandbox Code Playgroud)

格式是固定的,只有数字更改.我想阅读这个"123"并忽略其余部分,但要验证其余部分是否采用假定的格式.如果我使用scanf,我可以写:

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

然后通过检查结果我会知道该行是否格式正确.我正在寻找一些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());
Run Code Online (Sandbox Code Playgroud)

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

在那儿?

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

seh*_*ehe 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";
}
Run Code Online (Sandbox Code Playgroud)

打印

Successfully parsed (42)
Run Code Online (Sandbox Code Playgroud)

看到Live On Coliru

当然,提振精神是远远比这更强大了.但它也可以用于这样的快速解决方案!

完整样本

为后代保留的代码:

#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";
    }

}
Run Code Online (Sandbox Code Playgroud)