Reputation: 231
I've been learning C++ for about a month now, and as I've written programs I've noticed that enabling the user to cancel their input (during a cin loop) is a pain. For example, a program that takes user input and stores it in a vector would have a cin loop like this.
vector<int>reftest;
int number;
cout << "Input numbers for your vector.\n";
while(cin >> number)
reftest.push_back(number);
The ideal would be for the user to simply press enter, and for the program to exit the loop, but since whitespace isn't read I'm not sure how this would be handled. Instead, something ugly usually ends up being the case like telling the user to input a certain character to cancel their input.
Are there any certain methods that any of you use to handle user input?
Upvotes: 2
Views: 4093
Reputation:
I'm afraid there is no good way of doing this. Real-world interactive programs simply do not use formatted (or unformatted, come to that) input from a stream to read the keyboard - they use operating system specific methods.
Upvotes: 0
Reputation: 288
There are several ways to approach your problem. The easiest is probably to move out of a direct cin/cout loop and to use std::getline instead. Specifically, you could write something like:
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int main( int argc, char **argv )
{
vector<int> reftest;
while ( true )
{
string input;
getline( cin, input );
// You can do whatever processing you need to do
// including checking for special values or whatever
// right here.
if ( input.size() == 0 ) // empty input string
{
cout << "Assuming you're bored with the Entering Numbers game." << endl;
break;
}
else
{
int value;
// Instead of using the input stream to get integers, we
// used the input stream to get strings, which we turn
// into integers like this:
istringstream iss ( input );
while ( iss >> value )
{
reftest.push_back( value );
cout << "Inserting value: " << value << endl;
}
}
}
}
Other approaches include cin.getline() (which I'm not a big fan of because it works on char* instead of strings), using the cin.fail() bit to figure out whether or not the incoming value was any good, etc. And depending on your environment, there are probably many richer ways of getting user input than through iostreams. But this should point you towards the information you need.
Upvotes: 3
Reputation: 19181
How about making a second loop like this:
char option;
do
{
cout << "do you want to input another number? (y)es/(n)o..." << endl;
cin >> option;
if ( option == 'y' )
acceptInput(); // here enter whatever code you need
}
while ( option != 'n' );
Upvotes: 0