PDA

Click to See Complete Forum and Search --> : Type conversions


karanc
Dec 27th, 2001, 12:20 AM
Can anyone briefly explain to me how type conversion works in c ?

How do i convert a string(char array) to double type ?
Do I have to use the type conversion functions every time or will it convert implicitly in some cases ?

parksie
Dec 27th, 2001, 05:22 AM
There's very few implicit conversions with strings. Basically it'll convert char* to string, and that's about it.

If you want to convert to double, it's easier than going the other way:#include <cstdlib>

using namespace std;

int main() {
const char *s = "-5.6e-3";

double d = atof(s);

return 0;
}

karanc
Dec 27th, 2001, 10:39 AM
Does that mean i can use atof for both conversion to float and double types depending on the type of the variable on the left hand side ?

jim mcnamara
Dec 27th, 2001, 11:25 AM
whoa.

There are library functions in C that convert strings to floating point.

atof() converts a char string to a double.
atoi() converts a char string to an integer.
_ecvt() takes a double and makes a string out of it - backwards from atof().

There are other special functions that convert substrings to double, float, integer. strtod(), strtof(), strtol().

All of this is in Visual Studio Help, with examples.

jim mcnamara
Dec 27th, 2001, 11:28 AM
The standard way to convert any number to a string is with
sprintf()


int i;
double j;
char tmp[20];
memset(tmp,0x0,sizeof(tmp));
sprintf(tmp,"%f",j); // double to string
sprintf(tmp,"%d",i); // integer to string