int to char[]: What's the reciprocal of std::atoi?

Discussion in 'C++' started by Magig Boatman, Jul 11, 2003.

  1. I am completely stumped after many hours pouring through my books, but
    I need to write fractions. I have a method to convert a string
    expression representing a fraction as "n/d" into a float and separate
    numerator and denominator integers (using std::atoi(std::string)), but
    now I need to convert an integer variable numerator and denominator
    pair into a char array or std::string class as "n/d". How can this be
    done?

    Thanks!
    Mark
    Magig Boatman, Jul 11, 2003
    #1
    1. Advertising

  2. "Magig Boatman" <> wrote in message
    news:...
    > I have a method to convert a string expression representing a fraction as
    > "n/d" into a float and separate numerator and denominator integers (using
    > std::atoi(std::string)),


    std::atoi takes a const char *. I guess you're calling std::string's
    c_str() function and then passing the result to std::atoi? In any case, the
    preferred way to convert from a std::string to a number is to use
    std::istringstream. See the FAQ:

    http://www.parashift.com/c -faq-lite/misc-technical-issues.html#faq-38.2

    > now I need to convert an integer variable numerator and denominator
    > pair into a char array or std::string class as "n/d". How can this be
    > done?


    Use std::eek:stringstream. Again, see the FAQ:

    http://www.parashift.com/c -faq-lite/misc-technical-issues.html#faq-38.1

    Your code would probably look something like this:

    std::eek:stringstream oss;
    oss << n << '/' << d;
    return oss.str();

    --
    Russell Hanneken
    Russell Hanneken, Jul 11, 2003
    #2
    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. Schnoffos
    Replies:
    2
    Views:
    1,209
    Martien Verbruggen
    Jun 27, 2003
  2. trey

    newbie: char* int and char *int

    trey, Sep 10, 2003, in forum: C Programming
    Replies:
    7
    Views:
    403
    Irrwahn Grausewitz
    Sep 10, 2003
  3. Hal Styli
    Replies:
    14
    Views:
    1,629
    Old Wolf
    Jan 20, 2004
  4. John Smith
    Replies:
    6
    Views:
    5,324
    Mike Wahler
    Oct 31, 2005
  5. Replies:
    3
    Views:
    3,037
Loading...

Share This Page