[英]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
在緩沖區中。 您需要清除該錯誤狀態並擺脫輸入中剩余的字符。 您可以通過添加
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
在while循環之后。 clear
清除錯誤,並且忽略調用消除了輸入中剩余的任何字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.