#include <iostream>
#include <string>
#include <sstream>
template < typename T > std::string to_string( const T& value )
{
std::ostringstream os ;
os << value ;
return os.str() ;
}
template < typename T > T to_value( const std::string& str )
{
std::istringstream is(str) ;
T value ;
if( is >> value >> std::ws && is.eof() ) // success
return value ;
else // failed
// report error (throw something)
return T() ;
}
int main()
{
int i = 12345 ;
std::string str = to_string(i) ;
int j = to_value<int>(str) ;
std::cout << "i: " << i << " str: " << str << " j: " << j << '\n' ;
double d = 123.45 ;
str = to_string(d) ;
double e = to_value<double>(str) ;
std::cout << "d: " << d << " str: " << str << " e: " << e << '\n' ;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RyaW5nPgojaW5jbHVkZSA8c3N0cmVhbT4KCnRlbXBsYXRlIDwgdHlwZW5hbWUgVCA+IHN0ZDo6c3RyaW5nIHRvX3N0cmluZyggY29uc3QgVCYgdmFsdWUgKQp7CiAgICBzdGQ6Om9zdHJpbmdzdHJlYW0gb3MgOwogICAgb3MgPDwgdmFsdWUgOwogICAgcmV0dXJuIG9zLnN0cigpIDsKfQoKdGVtcGxhdGUgPCB0eXBlbmFtZSBUID4gVCB0b192YWx1ZSggY29uc3Qgc3RkOjpzdHJpbmcmIHN0ciApCnsKICAgIHN0ZDo6aXN0cmluZ3N0cmVhbSBpcyhzdHIpIDsKICAgIFQgdmFsdWUgOwogICAgaWYoIGlzID4+IHZhbHVlID4+IHN0ZDo6d3MgJiYgaXMuZW9mKCkgKSAvLyBzdWNjZXNzCiAgICAgICAgcmV0dXJuIHZhbHVlIDsKICAgIGVsc2UgLy8gZmFpbGVkCiAgICAgICAvLyByZXBvcnQgZXJyb3IgKHRocm93IHNvbWV0aGluZykKICAgICAgIHJldHVybiBUKCkgOwp9CgppbnQgbWFpbigpCnsKICAgICBpbnQgaSA9IDEyMzQ1IDsKICAgICBzdGQ6OnN0cmluZyBzdHIgPSB0b19zdHJpbmcoaSkgOwogICAgIGludCBqID0gdG9fdmFsdWU8aW50PihzdHI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