为什么 cin 不在 for 循环内执行?
Why is cin not executing inside for loop?
#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");
}
我想输入多项式方程的幂和系数。我能够将权力存储在向量中。但是在我用来输入系数的 for 循环中,cin 根本没有执行。如果有人能找出导致跳过 cin 语句的确切原因,我将不胜感激。
这里的问题是你告诉用户输入一个字符来结束
while (cin >> pow)
powers.push_back(pow);
虽然这有效,但它也会使 cin
处于错误状态并将字符留在缓冲区中。您需要清除该错误状态并删除输入中留下的字符。您可以通过添加
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
在 while 循环之后。 clear
清除错误,忽略输入中的所有字符。
#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");
}
我想输入多项式方程的幂和系数。我能够将权力存储在向量中。但是在我用来输入系数的 for 循环中,cin 根本没有执行。如果有人能找出导致跳过 cin 语句的确切原因,我将不胜感激。
这里的问题是你告诉用户输入一个字符来结束
while (cin >> pow)
powers.push_back(pow);
虽然这有效,但它也会使 cin
处于错误状态并将字符留在缓冲区中。您需要清除该错误状态并删除输入中留下的字符。您可以通过添加
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
在 while 循环之后。 clear
清除错误,忽略输入中的所有字符。