Reputation: 401
I am writing code that takes values from a user and stores it into a vector. The goal is that user can enter a said amount of values and they would be stored into a vector. The User will then be given the option to enter in another amount if he or she wishes and those values would also be stored in the same vector. However in order to terminate the inner while loop that allows the user to enter in the values, the user has to use EOF but that also ends my outer while loop. I do not know what a simple solution to this would be.
#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;
}
Upvotes: 0
Views: 488
Reputation: 117178
If the user closes his/her side of std::cin
you won't be able to do cin >> holder;
afterwards, so you need another way of letting the user stop entering numbers into the vector. Here's an alternative:
#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;
}
}
You could also take a closer look at std::getline
and std::stringstream
to make an even nicer user interface.
Upvotes: 1
Reputation: 136
You might be better of using getline than cin. getline looks for \n instead of EOF as far as I remember,
But I have not used C++ in some time so I might be wrong about that.
http://www.cplusplus.com/reference/string/string/getline/
Upvotes: 0