How do I terminate input?

Started by
4 comments, last by _Unicron_ 14 years, 3 months ago
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;
}

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

Please don't PM me with questions. Post them in the forums for everyone's benefit, and I can embarrass myself publicly.

You don't forget how to play when you grow old; you grow old when you forget how to play.

Not sure what you are asking? Do you wan't a terminate the loop when something
unique is inputted?
Edge cases will show your design flaws in your code!
Visit my site
Visit my FaceBook
Visit my github
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
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

Please don't PM me with questions. Post them in the forums for everyone's benefit, and I can embarrass myself publicly.

You don't forget how to play when you grow old; you grow old when you forget how to play.

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.

This topic is closed to new replies.

Advertisement