在内部while循环中使用EOF时结束的while循环

缺口

我正在编写从用户那里获取值并将其存储到向量中的代码。目标是用户可以输入所述数量的值,并将它们存储到向量中。然后,如果用户愿意,可以选择输入另一个金额,并且这些值也将存储在同一向量中。但是,为了终止允许用户输入值的内部 while 循环,用户必须使用 EOF,但这也结束了我的外部 while 循环。我不知道一个简单的解决方案是什么。

#include <iostream>
#include <vector>
#include<string.h>
using namespace std;


int main()
{
    int a;
    int holder, answer = 1;
    vector<int> v;
    vector<int> s;

    while (answer == 1) {
        cout << " Enter in a vector \n";
        while (cin >> a) {
            v.push_back(a);
        }
        s.insert(s.begin(), v.begin(), v.end());
        for (int i{ 0 }; i < s.size(); i++) {
            cout << s.at(i);
        }
        cout << " do you want to continue adding a vector? Type 1 for yes and 0 for no." << "\n";
        cin >> holder;

        if (holder == answer)
            continue;
        else
            answer = 0;
    }
    return 0;
}
泰德·林格莫

如果用户关闭他/她的一侧,std::cin您之后将无法执行此操作cin >> holder;,因此您需要另一种方式让用户停止将数字输入到向量中。这是一个替代方案:

#include <iostream>
#include <vector>
#include <string> // not string.h

int main() {
    int a;
    int holder, answer = 1;
    std::vector<int> v;
    std::vector<int> s;

    while(true) {
        std::cout << "Enter in a vector of integers. Enter a non-numeric value to stop.\n";
        while(std::cin >> a) {
            v.push_back(a);
        }
        s.insert(s.begin(), v.begin(), v.end());
        for(int s_i : s) {
            std::cout << s_i << "\n";
        }
        if(std::cin.eof() == false) {
            std::cin.clear(); // clear error state
            std::string dummy;
            std::getline(std::cin, dummy); // read and discard the non-numeric line
            std::cout << "do you want to continue adding a vector? Type "
                      << answer << " for yes and something else for no.\n";
            std::cin >> holder;

            if(holder != answer) break;
        } else
            break;
    }
}

您还可以仔细查看std::getlinestd::stringstream制作更好的用户界面。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章