繁体   English   中英

如何让我的程序在 C++ 中接受来自用户的不同输入?

[英]How do I allow my program to accept different inputs from the user in C++?

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

#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;
}

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

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

这是一个有效的和很少改进的实现。 在此,我们使用任何非数字输入终止循环,例如终止“。”:

#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;
}

这是 output:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM