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

时间:2019-05-02 14:23:51

标签: c++ visual-studio

我正在编写从用户处获取值并将其存储到向量中的代码。目的是用户可以输入所述数量的值,并将它们存储到向量中。然后,如果用户愿意,将为用户提供输入其他金额的选项,并且这些值也将存储在同一向量中。但是,为了终止允许用户输入值的内部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;
}

2 个答案:

答案 0 :(得分:1)

如果用户关闭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,以创建更好的用户界面。

答案 1 :(得分:0)

使用getline比使用cin更好。据我所知,getline会查找\ n而不是EOF,

但是我已经有一段时间没有使用C ++了,所以我对此可能是错的。

http://www.cplusplus.com/reference/string/string/getline/

相关问题