cin.get and cin.ignore help

I am using cin.get and cin.ignore to get values entered by the user all at once with spaces in between each input.
Example: 2 3 4 5 6 7 8 9

These values get put into an array. This program works perfectly except for one thing. If I don't put a "space" after the last value, then the program freezes. If I put a space after the last value then it works exactly like it is supposed to. What am I doing wrong?

1
2
3
4
5
6
7
8
9
10
11
template <class elementType>
void Buffer <elementType>::inputValues()
{
	for (int i = 0; i < size; i++)
	{
		elementType a;
		cin.get(a);
		cin.ignore(256, ' ');
		ptr[i] = a;
	}
}
Last edited on
Maybe this would work:
1
2
3
4
5
6
7
8
9
10
11
template <class elementType>
void Buffer <elementType>::inputValues()
{
    for (int i = 0; i < size; i++)
    {
        elementType a;
        cin >> ws;
        cin.get(a);
        ptr[i] = a;
    }
}


or this:
1
2
3
4
5
6
7
8
template <class elementType>
void Buffer <elementType>::inputValues()
{
    for (int i = 0; i < size; i++)
    {
        cin >> ptr[i];
    }
}
The first one worked thanks.

Do you mind telling me why?
What does the "ws" do? I thought it was just a variable but when I changed it to b it said b is undefined.
EDIT2: Just kidding sorry I was being lazy I just looked it up on the c++ reference.

I just want to understand why it works. Thanks for helping


EDIT: the second one works too. If you don't mind could you explain that one also? Why don't I need to ignore the "space" entered in between values?
Last edited on
As you can see from the documentation,
http://www.cplusplus.com/reference/istream/ws/
ws "Extracts as many whitespace characters as possible from the current position in the input sequence. The extraction stops as soon as a non-whitespace character is found."

In other words, if there is leading whitespace (before the actual value), it is removed. And if there is no whitespace, it does nothing.

Whitespace here means any of space, tab or newline.

The second version, the cin >> consumes leading whitespace, before extracting the required value.

Both of these are preferable to the use of cin.ignore(256, ' ');, as that really insists there must be either 256 characters ignored, or it finds an actual space.
Topic archived. No new replies allowed.