Question

I've got string like this:

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

The format is fixed, only the number changes. I'd like to read this "123" and ignore the rest, but verify that the rest of line is in assumed format. If I used scanf, I could write:

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

And then by checking the result I would know whether the line is in correct format. I'm looking for some std:: or boost:: method to do this, for instance using a modifier like this:

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());

Of course I could write it myself, but I can't believe that there is no simple method to do this using only std or boost.

Is there?

EDIT: Regex would be overkill for me in this case.

Was it helpful?

Solution

With Boost you can use Spirit's qi::match manipulator:

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

Prints

Successfully parsed (42)

See it Live On Coliru

Of course, Boost Spirit is vastly more powerful than this, but... it can also be used for quick solutions like this!

Full Sample

Code preserved for posterity:

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

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top