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

M

Magig Boatman

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
 
R

Russell Hanneken

Magig Boatman said:
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();
 

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,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top