Tien Hung
Tien Hung

Reputation: 155

C++: Error when inputting the second input after have done the first one already

I try to write the program to input a series of numbers and input how many numbers I want to sum.

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    int num;
    vector<int> number;

    cout << "Please enter some number (press '|' at prompt to stop):\n";
    while (cin >> num)
        number.push_back(num);

    int n, sum = 0;
    cout << "Please enter how many of the numbers you wish to sum, starting from the first:\n";
    cin >> n;
    
}

But when I input some number and stop my first input with '|', then it outputs the line "Please enter how many of..." and ends the compiler without inputting the variable n.

Upvotes: 1

Views: 72

Answers (1)

Asphodel
Asphodel

Reputation: 190

You can add cin.ignore() before taking in last argument, to ignore the extra characters that gets added to input stream (when you hit '\n' to input your value, it gets added to input stream and also other invalid inputs you may additionally add on same line). Probably want to add in cin.clear() to reset stream state beforehand as well.

#include <limits> // also include limits header

int main()
{
    int num;
    vector<int> number;

    cout << "Please enter some number (press '|' at prompt to stop):\n";
    while (cin >> num)
        number.push_back(num);

    int n, sum = 0;
    cout << "Please enter how many of the numbers you wish to sum, starting from the first:" << endl;
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin >> n;
}

Also, please note that prompt will stop no matter what noninteger you input for while loop.

Upvotes: 2

Related Questions