【问题标题】:How do I allow my program to accept different inputs from the user in C++?如何让我的程序在 C++ 中接受来自用户的不同输入?
【发布时间】:2021-01-24 06:46:59
【问题描述】:

我有一个允许用户将整数输入向量的程序。一旦用户完成了第一个向量,程序就会打印向量的内容以及它有多大,当假设用户能够将整数输入到第二个向量中时,问题出现在第一个向量之后。我的程序只是跳过了这一点,不让用户输入任何内容。代码如下。

#include <iostream>
#include <vector>

using namespace std;

void print1(vector <int> const& vector1) {
    std::cout << "\nThe elements of Vector 1 are: ";

    for (int v1{ 0 }; v1 < vector1.size(); ++v1) {
        cout << vector1.at(v1) << ' ';
    }
    std::cout << "\nThe size of Vector 1 is: " << vector1.size();
}

void print2(vector <int> const& vector2) {
    std::cout << "\nThe elements of Vector 2 are: ";

    for (int v2{ 0 }; v2 < vector2.size(); ++v2) {
        cout << vector2.at(v2) << ' ';
    }
    std::cout << "\nThe size of Vector 2 is: " << vector2.size();
}

int main() {
    vector <int> vector1(0);
    vector <int> vector2(0);

    int data1{ 0 };
    std::cout << "Enter data for Vector 1: ";
    while (cin >> data1) {
        vector1.push_back(data1);
    }
    print1(vector1);


    int data2{ 0 };
    std::cout << "\n\nEnter data for Vector 2: ";
    while (cin >> data2) {
        vector2.push_back(data2);
    }
    print2(vector2);

    return 0;
}

编辑******** 感谢 cmets 中的 Nathan,我最终要做的就是添加 cin.clear();就在第二个向量的代码上方。

【问题讨论】:

  • 您似乎一直在阅读,直到设置了 cin 的失败位。那时,后续的读取不会关闭;第二个while 循环的条件将立即为false。在阅读vector1vector2 之间,您需要clear
  • @NathanPierson 非常感谢,我对编程很陌生,在花了 30 分钟的时间之后,事实上它只是添加了 cin.clear();中间是惊人的。
  • 请您创建一个答案,以便将其从未回答的问题列表中删除。 @内森皮尔森

标签: c++


【解决方案1】:

在您的实现中,第一个循环没有退出。

这是一个有效的和小改进的实现。在这种情况下,我们使用任何非数字输入来终止循环,例如终止“。”:

#include <iostream>
#include <vector>

using namespace std;

void print_vector(vector <int> const& vector1) {

    for (int v1{ 0 }; v1 < vector1.size(); ++v1) {
        cout << vector1.at(v1) << ' ';
    }
}

void read_vector(vector <int>& vector1) {
    int data1{ 0 };
    while (cin >> data1) {
        vector1.push_back(data1);
    }

    cin.clear();
    string term;
    cin >> term;
}

int main() {
    vector <int> vector1(0);
    vector <int> vector2(0);

    std::cout << "Enter data for Vector 1: ";
    read_vector(vector1);
    std::cout << "\nThe elements of Vector 1 are: ";
    print_vector(vector1);
    std::cout << "\nThe size of Vector 1 is: " << vector1.size() << endl;

    std::cout << "Enter data for Vector 2: ";
    read_vector(vector2);
    std::cout << "\nThe elements of Vector 2 are: ";
    print_vector(vector2);
    std::cout << "\nThe size of Vector 2 is: " << vector1.size() << endl;

    return 0;
}

这是输出:

Enter data for Vector 1: 1 2 3.

The elements of Vector 1 are: 1 2 3
The size of Vector 1 is: 3
Enter data for Vector 2: 4 5 6.

The elements of Vector 2 are: 4 5 6
The size of Vector 2 is: 3

【讨论】:

    猜你喜欢
    • 2019-01-21
    • 2018-02-07
    • 2016-12-19
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2018-10-11
    相关资源
    最近更新 更多