Search code examples
c++scanfcinskip

Ignoring/skipping tokens using std::cin


With scanf one is allowed to skip matched tokens, simply adding * to the pattern, as in:

int first, second;
scanf("%d %*s %d", &first, &second);

Is there any equivalent approach with std::cin? Something like (of course, sparing the usage of additional variables):

int first, second;
std::cin >> first >> `std::skip` >> second;

Solution

  • It's not a simple task for input streams in C++ to do same thing. Function scanf gets all expected format: "%d %*s %d" and can look ahead to determine what's going on.

    On the other hand, operator >> just tries to satisfy current entry parameter.


    You have chances to write you own istream manipulator to eat inputs until reaching a digit.

    Try this my naive code:

    template<typename C, typename T>
    basic_istream<C, T>&
    eat_until_digit(basic_istream<C, T>& in)
    {
      const ctype<C>& ct = use_facet <ctype<C>> (in.getloc());
    
      basic_streambuf<C, T>* sb = in.rdbuf();
    
      int c = sb->sgetc();
      while (c != T::eof() && !ct.is(ctype_base::digit, c))
          c = sb->snextc();
    
      if (c == T::eof())
          in.setstate(ios_base::eofbit);
    
      return in;
    }
    
    int main()
    {
        int first, second;
    
        cin >> first >> eat_until_digit >> second;
    
        cout << first << " : " << second << endl;
    }
    

    You can extend and improve above code to achieve what you need.