Help using cin for a vector of ints

I am trying to read in an unknown number of ints into a vector using cin. This is my code:

1
2
3
4
 cout << "Input heap sizes: " << endl;
  while( cin >> input ) {
    v.push_back(input);
  }

I have tried various forms of the following:

1
2
3
4
5
6
7
 cout << "Input heap sizes: " << endl;
  while( cin >> input ) {
    if( cin.fail() ) break;
    if( cin.eof() ) break;
    v.push_back(input);
        cin.clear();
  }

But the loop never terminates no matter what I try. Any recommendations?
Last edited on
What type of variable is input? if it is a number of some kind then just entering a character should stop the first loop. But you should be able to force eof() by entering either Ctrl-D or Ctrl-Z (on a line by it's self), which key combination depends upon your operating system..

while( cin >> input )

>> is an operator that returns the cin object. The loop continues until cin fails to read whatever data type input is. So, if you type in a number, hit enter, repeat, or type in a set of numbers (1 2 3 4) and then hit enter, the cin object is still okay.

You could end your first piece of code with the following: (assuming input is a number type)
1 2 3 4 a

>> reads until it hits the "a", at which point cin is broken, thus ending the loop.

Not a very good solution though.

You can use peek() to help you if you are typing in a set of numbers:
1
2
3
4
5
while (cin.peek() != '\n')
{
  cin >> temp;
  v.push_back(temp);
}


If you don't want to do that, you can use a sentinal:
1
2
3
4
cout << "Enter numbers, negative to stop";
int temp;
while (cin >> temp && temp >= 0)  // For your use, zero seems a better sentinal than negative
  v.push_back(temp);


or
1
2
3
4
5
6
7
8
cout << "Enter numbers, negative to stop";
unsigned int temp;
while (cin.peek() != '-')
{ 
  cin >> temp;
  v.push_back(temp);
}
cin.ignore(80, '\n');

Last edited on
Topic archived. No new replies allowed.