Number conversion with string streams

Discussion in 'C++' started by Eugene, Jul 30, 2003.

  1. Eugene

    Eugene Guest

    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.
     
    Eugene, Jul 30, 2003
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mark Helm

    String to number conversion

    Mark Helm, Mar 5, 2004, in forum: XML
    Replies:
    0
    Views:
    416
    Mark Helm
    Mar 5, 2004
  2. Delali Dzirasa
    Replies:
    4
    Views:
    1,032
    Delali Dzirasa
    Sep 15, 2003
  3. Alessandro Monopoli

    STL string class and Number conversion

    Alessandro Monopoli, Mar 31, 2005, in forum: C++
    Replies:
    3
    Views:
    17,335
    msalters
    Mar 31, 2005
  4. Chinmoy Mukherjee

    ascii string to hex number conversion API

    Chinmoy Mukherjee, May 9, 2005, in forum: C++
    Replies:
    4
    Views:
    18,941
    Howard
    May 9, 2005
  5. Replies:
    14
    Views:
    1,042
    Simon Biber
    Nov 16, 2006
Loading...

Share This Page