inconsistent behavior with istream::ignore

What does the following program print for the value of ch if the input is: 45 kitten
what about if the input is: 45 mitten

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include  <iostream>

using namespace std;

int main()
{
  int x;
  char ch;

  cout << "Enter a values:";
  cin >> x;
  cin.ignore(1,'k');
  cin>>ch;

  cout << "x =" << x <<"  ch = "<<ch <<endl;
  return 0;
}


This does not follow the definition of ignore. Does anyone know why?
because operator >> leaves whitespaces in the stream.
cin.ignore(1,'k'); removes up to 1 character http://www.cplusplus.com/reference/iostream/istream/ignore/
Maybe I should clarify:

here is output for 45 kitten:
x =45 ch = i

here is output for 45 mitten:
x =45 ch = m

in both cases 1 whitespace character is ignored but with 45 kitten the k is also ignored.

I've read the reference documentation for ignore and this is taken from it:

"The extraction ends when n characters have been extracted and discarded or when the character delim is found, whichever comes first. In the latter case, the delim character itself is also extracted."

According to the documentation, the first thing that happens should end the extraction.
with cin.ignore(1,'k'); in my example, the first thing to happen is that 1 whitespace character is extracted. According to the documentation, the 'k' should not be extracted.
Last edited on
According to the documentation, the 'k' should not be extracted.


But then you stated that the documentation says:

In the latter case, the delim character itself is also extracted.
I see your point but the two cases are divided by an "or" so if 'k' is found first, it is extracted. Not if n characters are extracted and the next character is the delim character, then the delim character is also extracted.
Ah I see what you mean. I believe it is because the delim character is not counted as a part of the characters you are ignoring.
it does seem like that. I would like to see the implementation but I haven't been able to find it anywhere. Thanks.
Topic archived. No new replies allowed.