I find the following general solution to be an easy way to get console input without a lot of the hassles that newbies normally trip over.
template<typename T>
bool simple_input(std::istream& is, T& x, char delim = '\n');
template<typename T>
bool simple_checked_input(std::istream& is, T& x, char delim = '\n');
The idea is that after each call, cin will be left in a good state and with no leftover characters in the stream. Numbers, characters, and strings can all be read in the same way with this function. Here is an example usage:
Code:
#include <iostream>
#include <string>
#include "simple_input.h"
int main()
{
using namespace std;
using namespace jlou;
string s;
cout << "Enter a line of text: ";
simple_input(cin, s);
cout << "The line of text read in was: " << s << endl;
int i;
cout << "Enter an int: ";
if (simple_input(cin, i))
cout << "The number read in was: " << i << endl;
else
cout << "Sorry, invalid int!" << endl;
double d;
cout << "Enter a double: ";
while (!simple_input(cin, d))
{
cout << "Invalid double! Try again: ";
}
cout << "The double read in was: " << d << endl;
}
And here is the basic implementation. I've attached a file that can be included and used as is, and contains special code for VC++ 6.0 if that is your compiler.
Code:
#include <istream>
#include <ios>
#include <string>
#include <limits>
namespace jlou
{
template<typename T>
inline bool simple_input(std::istream& is, T& x, char delim = '\n')
{
if (is >> std::noskipws >> x >> std::skipws && (is.eof() || is.get() == delim))
return true;
x = T();
is.clear();
is.ignore(std::numeric_limits<std::streamsize>::max(), delim);
return false;
}
template<>
inline bool simple_input<std::string>(std::istream& is, std::string& x, char delim)
{
if (std::getline(is, x, delim))
return true;
x.clear();
is.clear();
return false;
}
template<typename T>
inline void simple_checked_input(std::istream& is, T& x, char delim = '\n')
{
if (!simple_input(is, x, delim))
throw std::ios_base::failure("input format not valid");
}
}
I posted this before on this site a while ago, but I've updated it since with input from other forums.