/* Lecture code 16.0
 *
 * StringToInteger function, complete with exception-handling facilities.
 */

#include <iostream>
#include <string>
#include <sstream>
#include <stdexcept> // For domain_error
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 domain_error("String does not start with 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 domain_error("String contains unexpected characters.");
	
	return result;
}

int main() {
	/* Try calling StringToInteger and printing the result. */
	try {
		cout << StringToInteger("137") << endl;
	}
	/* If an error occurs, print out what went wrong. */
	catch(const exception& rex) {
		cout << rex.what() << endl;
	}
	return 0;
}