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

标签 c++ visual-studio

我正在编写代码,从用户那里获取值并将其存储到 vector 中。目标是用户可以输入一定数量的值,并将它们存储到 vector 中。然后,用户将可以选择输入另一个金额(如果他或她愿意),这些值也将存储在同一 vector 中。但是,为了终止允许用户输入值的内部 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; 之后,因此您需要另一种方式让用户停止在 vector 中输入数字。这是一个替代方案:

#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 以创建更好的用户界面。

关于c++ - 在内部 while 循环中使用 EOF 时结束的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55954546/

相关文章:

c++ - 为什么与比较类不在同一个命名空间中时,std::variant无法找到operator <()

c++ - 这个 Visual Studio 编译器错误 'divide or mod by zero' 是一个错误吗?

visual-studio - 在 Visual Studio 中使用特定的 TypeScript 编译器版本

c++ - Visual Studio 中的安全开发生命周期检查选项是什么?

visual-studio - 为什么 VS2013 会重置垂直拆分的 XAML 窗口?

windows - Visual Studio shell(独立 shell)有什么用?

c++ - 从模板中的子表达式中提取类型

c++ - 为什么 GCC 不强制 __attribute__((pure)) 函数中的参数为常量?

c++ - Sizeof 指向数组的指针

c# - 在 C# 中调试时,Visual Studio 如何评估属性?