Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

convert between float and char* (prefer to use sscanf )

Posted on 2004-10-18
6
472 Views
Last Modified: 2008-01-09
I have built my own version of a fraction class, with the following variables:
int myNum
int myDen
char* outputString


My ToString() method outputs the a fraction like this:

// return a string for the programmer to use in his program. (using <sprintf>)
char *Fraction::ToString()
{
       //allocate memory for <outputString>
       char buf[500];
       outputString= (char*) new char[(int)strlen(itoa(myNum, buf, 10)) + 1 + (int)strlen(itoa(myDen, buf, 10)) +1];

       //print <outputString>
       sprintf(outputString, "%d/%d", myNum, myDen);
       return outputString;
}



My ToFloat() function will have to store the fraction as a float, and make it available for output. Should I use sscanf()? here's what I have so far for my ToFloat() function:

//Convert a Fraction to a float for outputting pruposes, or use elsewhere in the main program code.
float Fraction::ToFloat()
{
       if (myDen != 0){
               ToLowestTerms();
      
               //convert the fraction to a float, then make this value a char*
      char temp[100] = (char*)((float)(myNum / myDen));//the float operator has already been overridden

      sscanf(temp, "%f", this->theString);//store this (char*)float in memory
      return this->theString;

       }else{
      return 0.0;
       }
}


I need this ASAP, and your help is much appreciated.
an aspiring programmer
0
Comment
Question by:cnesb860
  • 3
  • 2
6 Comments
 
LVL 4

Accepted Solution

by:
pankajtiwary earned 150 total points
ID: 12342999
Hi cnesb860,

There are a few things that I would like to comment on.

When you are wroking with C++, it gives you a hell lot of easy to use tools as compared with C so for I/O I advise you to use cin and cout similarly, in place of sprintf and sscanf, you can use stringstream classes. Those are much easier to use and many problems will be handled by the language itself. So, I would like to change your ToString() function to

string tostring() {
    ostringstream o ;
    o << num << "/" << den << endl ;
    return o.str();
}

Similarly, the ToFloat() function will be something like

string tofloat() {
    ostringstream o ;
    o << static_cast<float>(num)/den << endl ;
    return o.str();
}

You can do whatever you want to do with the resulted strings.

Cheers!
0
 
LVL 1

Author Comment

by:cnesb860
ID: 12343234
That helped a little. Thanks. But it would be nice if I could allocate the char* and place the values into memory. Also, which way would be more efficient for future reference? It would be nice to be able to follow this psuedo-code:

//notice the return type
float Fraction::ToFloat() {

     //allocate char* <outputString> using keyword new if this hasn't already been done

     //convert the fraction from the form <intNum/intDen> to the form <float>

     //store the <float> in the char* <outputString> for later access

     //return the float value

}

Thanks again for your help pankajtiwary. I may do it that way for my next solution, I need to return a float for this specific problem. I am just curios how to store that <float> in memory for use elsewhere.
0
 
LVL 15

Assisted Solution

by:efn
efn earned 150 total points
ID: 12344104
    //allocate char* <outputString> using keyword new if this hasn't already been done

It would be simpler just to have a string member or a large enough character array member.

     //convert the fraction from the form <intNum/intDen> to the form <float>

pankajtiwary has shown you how to do this.  His (or her) method will work better than your original code, because it converts one of the terms to float before doing the division, so you get floating point division.  The original code did the division first, then converted the result to float.  Because the terms are integers, you would get integer division, which truncates the fractional part--not appealing in a fraction class.

     //store the <float> in the char* <outputString> for later access

If you want to use a character array instead of a string object, you can use the sprintf function to format a floating-point number into it.
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 1

Author Comment

by:cnesb860
ID: 12344569
Thanks to you both. You did a good job of explaining exactly what your code was doing, which is helpful to as "aspiring programmer" like me. and thanks for being so quick on the draw, as this is for a school assignment. :)
0
 
LVL 1

Author Comment

by:cnesb860
ID: 12364823
I have a question about the method that you recommended I use. Is stringstream'ing compatible with command line AND gui programs?

I ask b/c I am working on several different classes which are basicly my own data types. Whatever way I build my classes, I want something with the most reusability so I only have to write this stuff once.

Thanks a bunch to all.
0
 
LVL 15

Expert Comment

by:efn
ID: 12365820
The most universal form is probably a character array, but you can convert a standard string to a character array with the c_str function.  So in return for the convenience of using a string object, when you want to pass it to a function that expects a character array, you have to call this function.

If all you are going to do with the string is pass it to functions that want character arrays, you might as well keep it in a character array.  If you want to do more ambitious things with it, you might consider using a string object.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question