在push_back cin不起作用之后

mon*_*ony 0 c++

我有这个代码的问题:

int main()
{
    int x, sum = 0, how_many;
    vector<int> v;

    cout << "Write few numbers (write a letter if u want to end)\n";

    while (cin >> x)
    {
        v.push_back(x);
    }

    cout << "How many of those first numbers do u want to sum up?" << endl;
    cin >> how_many;

    for (int i = 0; i < how_many; ++i)
    {
        sum += v[i];
    }
    cout << "The sum of them is " << sum;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题是控制台不让我写入某些内容how_many并发生错误.当我在cout << "Write few..."它之前放置第6行和第7行时,一切都完美无缺.有人能告诉我为什么会这样吗?

Mik*_*our 6

cin无法将输入转换为整数时,循环结束,整数cin处于错误状态.它还包含最后一行输入.除非您清除坏状态,否则任何进一步的输入都将失败:

cin.clear();    // clear the error state
cin.ignore(-1); // ignore any input still in the stream
Run Code Online (Sandbox Code Playgroud)

(如果您喜欢详细程度,则可以指定std::numeric_limits<std::stream_size>::max(),而不是依赖于转换为-1无符号类型的最大值).