Ignoring / skipping tokens using std :: cin

With scanf allowed to skip matching markers by simply adding * to the pattern, as in:

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

Is there an equivalent approach with std::cin ? Something like (of course, saving the use of additional variables):

 int first, second; std::cin >> first >> `std::skip` >> second; 
+6
source share
3 answers

It is not an easy task for input streams in C ++ to do the same. The scanf function gets the entire expected format: "%d %*s %d" and can look ahead to determine what is happening.

On the other hand, the >> operator is simply trying to satisfy the current input parameter.


You have a chance to write your own istream manipulator so that there are inputs before 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 expand and improve the code above to achieve what you need.

+3
source

You might be looking for the C ++ String Toolkit Library .

Check it out for more example.

Or you can try using the ignore function:

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

Something like that: -

 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; 
+3
source

You can just use a dummy variable

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

but there is no direct equivalent to AFAIK.

+2
source

Source: https://habr.com/ru/post/954841/


All Articles