/* Lecture code 13.0
 *
 * StringToInteger function, complete with exception-handling facilities.
 */

#include <iostream>
#include <string>
#include <sstream>
#include <stdexcept>
using namespace std;

/* Converts a string representation of an integer into an int. */
int StringToInteger(const string& str)
{
	stringstream converter;
	converter << str;
		
	/* Try to read an int. */
	int result;
	converter >> result;
		
	/* If we failed to read an int, do some form of error handling. */
	if(converter.fail())
		throw runtime_error("Couldn't read in an integer.");

	/* See if we can read anything else after the int.  If so, fail. */
	char remaining;
	converter >> remaining;
		
	/* If the stream didn't break, something's wrong. */
	if(!converter.fail())
		throw runtime_error("Couldn't read in an integer.");
	
	return result;
}

int main()
{
	try
	{
		cout << StringToInteger("137") << endl;
	}
	catch(const runtime_error& rex)
	{
		cout << rex.what() << endl;
	}
	return 0;
}