我正在编写代码,从用户那里获取值并将其存储到 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::getline
和 std::stringstream
以创建更好的用户界面。
关于c++ - 在内部 while 循环中使用 EOF 时结束的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55954546/