Question

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;
Was it helpful?

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.

OTHER TIPS

You are probably looking for C++ String Toolkit Library.

Check this for more example

Or you may try with ignore function like this:

std::cin >> val1;
std::cin.ignore (1234, ' ');
std::cin >> val3;

Something like this:-

template <class charT, class traits>
inline std::basic_istream<charT, traits> &
ignoreToken (std::basic_istream<charT, traits> &strm)
{
    strm.ignore (1234, ' ');
    return strm;
}

And then use like:

cin >> val1 >> ignoreToken >> val3 >> ignoreToken >> val5;

You can simply use a dummy variable

int first, second;
std::string dummy;
cin >> first >> dummy >> second;

but there's no direct equivalent AFAIK.

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