Reputation: 87
#include <iostream>
#include <vector>
using namespace std;
typedef vector<double> vec; //vec now acts like a datatype
int main()
{
vec powers; //stores powers of x in the objective function
vec coefficients; //stores coefficients of x in the objective function
double pow;
double coeff = 0;
cout << "Enter powers of x present in the objective function and enter any character to stop" << endl;
cout << "REMEMBER TO ENTER 0 IF CONSTANT EXISTS!" << endl;
while (cin >> pow)
powers.push_back(pow); //Working fine
cout << endl;
for (vec::iterator iter_p = powers.begin(); iter_p != powers.end(); iter_p++)
{
double coeff;
cout << "Enter coefficient of the (x^" << *iter_p << ") term: ";
cin >> coeff; //THIS IS NOT EXECUTING
coefficients.push_back(coeff); //NOT WORKING EITHER
}
cout << endl;
return 0;
system("pause");
}
I want to input powers of a polynomial equation along with coefficients. I am able to store the powers in a vector. But in the for loop I am using to input coefficients, cin is simply not executing. I would be much obliged if someone could out what exactly is causing cin statement to be skipped.
Upvotes: 0
Views: 707
Reputation: 180500
The issue here is you tell the user to enter a character to end
while (cin >> pow)
powers.push_back(pow);
While that works, it also puts cin
in an error state and leaves the character in the buffer. You need to clear that error state and get rid of the character left in the input. You would do that by adding
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
after the while loop. clear
clears the errors and the call to ignore gets rid of any characters left in the input.
Upvotes: 2