while(cin >>x) terminates program

Jan 23, 2009 at 6:08pm
I have just started learning C++. Every time I use a while (cin>>x) loop, when the loop is terminated no other input is accepted.

Please can someone explain why this is.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
	vector<int> vec;
	int x;
	int sum = 0;
	cout << "Please enter the numbers: \n\n";
	while (cin>>x){
		vec.push_back(x);
	}
	for (int i = 0; i != vec.size(); ++i){
		cout << vec[i] << ' ' ;}
	int numtosum;
	cout << "How many numbers would you like to sum? \n\n";
	cin >> numtosum;
}


I enter an invalid character say '|' to exit the while loop, but this seems to print the next line and exit the program. No prompt is shown to input the next value.

Thanks for any help.
Last edited on Jan 23, 2009 at 8:42pm
Jan 23, 2009 at 7:37pm
It is because of the way cin works:

1. It ignores whitespaces (space, tab, newline)
2. It reads Input to the next whitespace
3. It leaves the whitespace in the buffer

So, if you type "| <Enter>" the newline character is still in the buffer, is read by "cin >> numtosum;" and the program exits. So, either you type
cin.ignore(1000,'\n')
before cin >> numtosum;

or you use getline() (i would recommend this)

Here is more information about getline() and user input
http://www.cplusplus.com/forum/articles/6046/
Jan 23, 2009 at 7:51pm
Thanks for the reply.

cin.ignore doesn't wok either I just get the same result.

Can you use getline() in a while loop?

and is getline not just for strings?
Last edited on Jan 23, 2009 at 8:28pm
Jan 23, 2009 at 8:28pm
cin.ignore(1000,EOF)
1000 - means in how long stream will be the EOF ignored
Jan 23, 2009 at 8:29pm
and for the getline, you can try it and you will see
Jan 23, 2009 at 8:41pm
Still no joy with cin.ignore(1000,EOF)

I'm putting it before the cin >> numtosum line. I'm getting the same result as before.

I'm working through the new Stroustrup book and this is the way he says to do it. This is why I am surprised it doesn't work.
Jan 23, 2009 at 10:09pm
Maybe you should also use cin.clear() since inputting invalid data puts cin into an error state.
Jan 25, 2009 at 7:36pm
1
2
3
while(getline(cin, input)) {
 // do stuff with input
}

is perfectly valid.
Topic archived. No new replies allowed.