MegaNoob
MegaNoob

Reputation: 91

C++ program does not allow me to give a second input

I have two consecutive inputs, however, my program ends before allowing me to have my second input and just runs till the end, so:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
      vector<double>v1;


    for(double temp1; cin >> temp1;)
        v1.push_back(temp1);

        cout <<  "input1";

    vector<double>v2;

    for (double temp2; cin >> temp2;)
        v2.push_back(temp2);

    cout << "input2";

    return 0;
}

I will be given the opportunity for input in the first for loop, however, after that, it doesn't let me give a second input and just goes on to print "input2".

Upvotes: 0

Views: 582

Answers (1)

Camwin
Camwin

Reputation: 413

It is ok to use the fail state of std::cin this way. You just need to reset std::cin before it can be used again.

#include <iostream>
#include <vector>

using namespace std;

int main()
{
      vector<double>v1;


    for(double temp1; cin >> temp1;)
        v1.push_back(temp1);
    
    cin.clear(); //clear the error
    cin.ignore(1000, '\n'); //ignore characters until we reach \n

    cout <<  "input1";

    vector<double>v2;

    for (double temp2; cin >> temp2;)
        v2.push_back(temp2);

    cout << "input2";

    return 0;
}

You could also #include <limits> and call

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

instead, to ignore unlimited characters until \n is reached.

Upvotes: 1

Related Questions