/* Lecture code 1.0
 *
 * 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)
	{
		/* Fill a stringstream with data read from GetLine().  This means that the user cannot
		 * gum up the input with extraneous data or put cin into a fail state.
		 */
		stringstream converter;
		converter << GetLine();
		
		/* Try to read an int out of the stream. */
		int result;
		converter >> result;
		
		/* If we failed to read in an integer, we need to report an error. */
		if(converter.fail())
			cout << "Please enter an integer." << endl;
		else
		{
			/* Otherwise, we know that we've successfully extracted an integer, but there might
			 * be some extra data lying around in the string that could be problematic.  To
			 * check if this is the case, we'll try to read a single character from the stream.
			 * If this succeeds, there's extra data lying around and we can report an error.
			 * Otherwise, if this fails, we know that the input was an int and only an int and
			 * we can report the result to the caller.
			 */
			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;
		}
		
		cout << "Retry: ";
	}
}