Variable Type Conversion

I am not that new, but do consider myself to be an amature due to my lack of knowledge of the winAPI, and Classes. But those things aside, I have a problem: Variable type conversion.

Right now, I am writing functions that will take the variable I want converted, and return a variable of the conversion I want. Here is an example:

(completely hypothetical)
I have a 141 question test. I have done 23 of the questions so far.

1
2
int total_questions = 141
int questions_done = 23


I want to know the percent of the questions I have answered.

float percent_answered = (total_questions / questions_done);

The only problem is that if I run a program like that, it will cause problems trying to convert an integer value into a float value through the process of division. So, we will convert these integers to floats through a special function I wrote:

percent_answered = (int_flo(total_questions) / int_flo(questions_done));

The only problem is that this is not as efficient as I would like it to be. It writes the value I give it to a file, opens the file as 'in', and reads the informations as the new variable type. This is extremely inefficient for things like progress bars. Since I have not been able to find a conversion function online, I will ask you guys. This is NOT HOMEWORK. I am learning this by myself, and would greatly appreciate your help.

All I want to know is: is there a way to convert a variable of type "type", to any other type of variable? (string to int, int to float, int to string, etc....)

Thank you for your time!
A simple cast should be several millions times faster than your method:
percent_answered = float(total_questions) / questions_done;

Note that when one of the operands is a floating point number, the other one will be promoted automatically, as shown above.

Casts do not work for strings, but there are functions like to_string in C++11 and boost's lexical_cast that solve the problem.
Last edited on
numeric type to numeric type (like an int to a float) can be done with a simple cast:

1
2
3
int foo = 5;
float bar = static_cast<float>(foo);  // verbose C++ style cast
float baz = (float)(foo);  // less verbose C style cast 


For converting to and from a string, I think C++11 added some convenience functions for that but I dont' remember what they are offhand so I'll let someone else field it.

For the record:
total_questions / questions_done
is the wrong way to calculate the percentage

To add another way without an explicit cast:

float percent_answered = 1.0f* questions_done/total_questions
@guestgulkan I know, and it doesn't matter. I know how to calc percentages. obviously part/total, but that is besides the point.

@everyone else

ty for your help.
Topic archived. No new replies allowed.