C++:在完成第一个输入后输入第二个输入时出错

发布于 2025-01-09 13:57:23 字数 597 浏览 2 评论 0原文

我尝试编写程序来输入一系列数字并输入我要求和的数字。

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    int num;
    vector<int> number;

    cout << "Please enter some number (press '|' at prompt to stop):\n";
    while (cin >> num)
        number.push_back(num);

    int n, sum = 0;
    cout << "Please enter how many of the numbers you wish to sum, starting from the first:\n";
    cin >> n;
    
}

但是,当我输入一些数字并用 '|' 停止我的第一个输入时,它会输出行 “请输入多少...” 并结束编译器,而不会输入变量n

I try to write the program to input a series of numbers and input how many numbers I want to sum.

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    int num;
    vector<int> number;

    cout << "Please enter some number (press '|' at prompt to stop):\n";
    while (cin >> num)
        number.push_back(num);

    int n, sum = 0;
    cout << "Please enter how many of the numbers you wish to sum, starting from the first:\n";
    cin >> n;
    
}

But when I input some number and stop my first input with '|', then it outputs the line "Please enter how many of..." and ends the compiler without inputting the variable n.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

定格我的天空 2025-01-16 13:57:23

您可以在接受最后一个参数之前添加 cin.ignore() ,以忽略添加到输入流的额外字符(当您点击 '\n' 输入您的值时,它会被添加到输入流以及您的其他无效输入可以在同一行另外添加)。可能还想添加 cin.clear() 来预先重置流状态。

#include <limits> // also include limits header

int main()
{
    int num;
    vector<int> number;

    cout << "Please enter some number (press '|' at prompt to stop):\n";
    while (cin >> num)
        number.push_back(num);

    int n, sum = 0;
    cout << "Please enter how many of the numbers you wish to sum, starting from the first:" << endl;
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin >> n;
}

另外,请注意,无论您在 while 循环中输入什么非整数,提示都会停止。

You can add cin.ignore() before taking in last argument, to ignore the extra characters that gets added to input stream (when you hit '\n' to input your value, it gets added to input stream and also other invalid inputs you may additionally add on same line). Probably want to add in cin.clear() to reset stream state beforehand as well.

#include <limits> // also include limits header

int main()
{
    int num;
    vector<int> number;

    cout << "Please enter some number (press '|' at prompt to stop):\n";
    while (cin >> num)
        number.push_back(num);

    int n, sum = 0;
    cout << "Please enter how many of the numbers you wish to sum, starting from the first:" << endl;
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin >> n;
}

Also, please note that prompt will stop no matter what noninteger you input for while loop.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文