【发布时间】: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。在阅读vector1和vector2之间,您需要clear。 -
@NathanPierson 非常感谢,我对编程很陌生,在花了 30 分钟的时间之后,事实上它只是添加了 cin.clear();中间是惊人的。
-
请您创建一个答案,以便将其从未回答的问题列表中删除。 @内森皮尔森
标签: c++