How do I terminate input?

This topic is 2980 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

For example, let's say I can enter 1,000,000 integers into a vector. But, in reality, that value could be anywhere from 0 - 1,000,000. What do I do? I can't do anything like "Press q to quit".
[source#include <iostream>
#include <vector>

using namespace std;

int main()

{

vector<int> n;
vector<int>::iterator pd;
unsigned long temp;
unsigned long ch = 1000001;

//enter numbers into the vector
while (cin >> temp)
{
n.push_back(temp);
}

return 0;
}



Share on other sites
If you want to intentionally limit the size of a vector, you can check vector::size() before you do a push_back.

Share on other sites
Not sure what you are asking? Do you wan't a terminate the loop when something
unique is inputted?

Share on other sites
The user is supposed to be able to enter 0 to 10^6 integers. Then I have to sort the integers from least to greatest.

My question was how do I know if the user stops before he reaches 10^6...for example, if he enters 500 integers and wants to stop.

But I think I have to use a different method than this. ;o

Share on other sites
Quote:
 I can't do anything like "Press q to quit".

Why not? If you want to avoid a lot of complex checking of input and you trust the user to follow instructions, you can prompt to enter something invalid and use cin.fail().
cout << "Enter 'q,enter' to terminate input."; // I think ctrl-Z works as wellcin >> temp;while( !cin.fail() ) {   n.push_back(temp);   cin >> temp;}// do your sorting - n.size() gives you the number of inputs

Share on other sites
There are also a couple of commands that are OS specific:

Ctrl+z on Windows
Ctrl+d on Linux/Mac

If I remember correctly. Then press enter.

The size() function on the vector will give you the number of elements it contains.