简体   繁体   English

为什么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");
}

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. 但是在我用于输入系数的for循环中,cin根本没有执行。 I would be much obliged if someone could out what exactly is causing cin statement to be skipped. 如果有人能找出导致cin语句被跳过的确切原因,我将倍感荣幸。

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. 在此有效的同时,它也会将cin置于错误状态,并将字符cin在缓冲区中。 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. 在while循环之后。 clear clears the errors and the call to ignore gets rid of any characters left in the input. clear清除错误,并且忽略调用消除了输入中剩余的任何字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM