Number conversion with string streams

E

Eugene

I'm working on a program which needs to convert a string to various data
types. I created a function using string streams and templates to do just
that:

template<typename T>
bool StringToNumber(string & s, T & number)
{
istringstream iss(s);

iss >> number;

return !iss.fail();
}

This function works great. It even checks the magnitude of the number in
the string and fails if the string number is too big to fit into the given
datatype.
Here's the problem: It converts chars differently than other types.
Example:
string s = "123";
char num;
StringToNumber(s, num); // num == '1'

How can I get the function to convert "123" into the number 123 not the
character '1' while still checking the magnitude so that a string like "500"
will fail to convert into a char.

Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top