Sign in to follow this  
OneThreeThreeSeven

How do I terminate input?

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 this post


Link to post
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 this post


Link to post
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 well
cin >> temp;
while( !cin.fail() ) {
n.push_back(temp);
cin >> temp;
}
// do your sorting - n.size() gives you the number of inputs

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this