/* Lecture code 1.2
 *
 * The simpio.h library functions.  Feel free to experiment around with this code
 * and see what other input functions you can build!
 */

#include <iostream>
#include <sstream> // For stringstream
#include <string>  // Next two lines replace genlib.h
using namespace std;

/* Use getline to read from cin and return the read string. */
string GetLine()
{
	string result;
	getline(cin, result);
	return result;
}

/* Read an integer, prompting until the user enters valid data. */
int GetInteger()
{
	while(true)
	{
		stringstream converter;
		converter << GetLine(); // Read data and load into the stream.
		
		/* Try to read an int. */
		int result;
		converter >> result;
		
		/* If we read an int successfully, see if anything's left over. */
		if(!converter.fail())
		{
			/* Try to read a single char.  In class we used a string, but
			 * this approach works as well.
			 */
			char remaining;
			converter >> remaining;
			
			/* If the stream broke, we ran out of characters and are done. */
			if(converter.fail())
				return result;
			else
				cout << "Unexpected character: " << remaining << endl;
		}
		else
			cout << "Please enter an integer." << endl;
		
		cout << "Retry: ";
	}
}