• Advertisement
Sign in to follow this  

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.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement