Reputation: 1275
vector<int> a;
vector<int> b;
int temp_holder;
cout << "\n Give the first ints \n" ;
while (cin >> temp_holder)
a.push_back(temp_holder);
cout << "\n Give the second ints \n";
while (cin >> temp_holder)
b.push_back(temp_holder);
When i press ctrl + z
for the first while loop the second also automatically ends. What is happening and how to fix it and is this the most efficient way to take values into a vector using while(cin >> var);
Thank you!
Upvotes: 1
Views: 82
Reputation: 206717
Your strategy is flawed.
The first while
loop will end only when there is no more input or there is an error in the input.
You can rely on the error to break the loop, clear the error state of the stream, ignore the rest of the line, and then continue to read the elements of the second vector
in the second while
loop.
cout << "\n Give the first ints \n" ;
while (cin >> temp_holder)
a.push_back(temp_holder);
// If EOF is reached, there is nothing more to read.
if ( cin.eof() )
{
// Deal with EOF.
}
// Clear the error state.
cin.clear();
// Ignore the rest of the line.
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Continue to read the elements of the second vector.
cout << "\n Give the second ints \n";
while (cin >> temp_holder)
b.push_back(temp_holder);
Using this approach, you can use
1 2 3 4 5
xxxx
10 20 30 40 50
as your input. The numbers before xxxx
will be read and stored in the first vector while those after xxxx
will be read and stored in the second vector.
Upvotes: 0
Reputation: 1
When i press ctrl + z for the first while loop the second also automatically ends.
CTRL+Z invalidates the cin
stream state (being at eof
). Thus any further calls like
cout << "\n Give the second ints \n";
while (cin >> temp_holder)
b.push_back(temp_holder);
will fail.
You could use std::getline()
to get the first and second set of integer value separately. This requires to enter a white space separated set of numbers, and let the user press the ENTER key to indicate the whole set is entered.
Then you can use std::istringstream
to extract the numbers to the vectors as needed.
Upvotes: 0