// B8.cpp - convert string to numeric type #include #include #include using namespace std; ////// start of required answer ///////////////////// template T convert(const string &s) { T temp; istringstream in(s.c_str()); if(!in.good()) { string errorStr = "error creating istringstream"; throw exception(errorStr.c_str()); } in >> temp; if(!in.eof() && !in.good()) { string errorStr = "error converting string "; errorStr += s; errorStr += " to type "; errorStr += typeid(temp).name(); throw exception(errorStr.c_str()); } return temp; } ////// end of required answer /////////////////////// void main() { try { string test[] = { "-73", "3.1415927", "2.5xyz", "<>[]{}" }; for(int i=0; i<4; i++) { cout << "\n the string is \"" << setw(10) << test[i] << "\" and the converted value is " << convert(test[i]); } } catch(exception &e) { cout << "\n--- " << e.what() << " ---"; } cout << "\n\n"; }