cin ignored

Hi everyone,

I don't understand why it happens. When the while loop ends, the program jumps through all the steps and ignores the cin>>sumcount...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include "../std_lib_facilities.h"

// Program to grow a vector by prompting user and calculating sum of numbers in the vector
// according to how many numbers the user wants to sum.

int main()

{
    int sum=0;
    int sumcount;
    vector<int> numbers;

//Prompting user to grow vector

   cout<< "Type in numbers. Enter a letter to stop\n";
   int number;
    while (cin>>number)
{
    numbers.push_back(number);

    }

//After getting out of the loop, the program doesn't wait for the user to cin>>sumcount and jumps through all the steps until he finishes...

  cout<< "How many numbers would you like to sum?\n";
  cin>>sumcount;

    if (sumcount<numbers.size())
    {

    for (int i=0; i<sumcount; ++i)
    {
        sum+=numbers[i];
    }
    }
  cout<<"Sum of " <<sumcount<<" first numbers = "<<sum;


    }
Hi,
After the while-loop, try adding these two lines and see the way your program will go.
1
2
cin.clear();
cin.ignore();
It didn't work...
In order to be able to break the while loop, you must input in a way that make the program produce an input error.

So firstly, you give us an output example.
Last edited on
closed account (48T7M4Gy)
.
Last edited on
Better yet, you can use this :
1
2
  cin.clear();
  cin.ignore(numeric_limits<streamsize>::max(),'\n');


Need to include an additional header <limits>
Last edited on
I see... How can I break out of the loop by pressing a letter without producing an error?
> I see... How can I break out of the loop by pressing a letter without producing an error?
So you are trying to say that you want to handle the input error in the while loop in a peaceful way without having to break the loop? You want the while-loop to exit manually, not automatically?
Yes exactly...

And

cin.ignore(numeric_limits<streamsize>::max(),'\n');

didn't work either
You may try this while-loop :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
while (1)
{
    cout << "Input a number (-1 to exit) : "; 
    cin >> number;

    if(!cin)
    {
        cin.clear(); 
        cin.ignore(1000, '\n');
        cout << "Invalid value. Try again.\n\n";
        continue;
    }
    
    if(number == -1) break;
    numbers.push_back(number);
}
Topic archived. No new replies allowed.