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 ?
Printable View
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 ?
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:Code:#include <cstdlib>
using namespace std;
int main() {
const char *s = "-5.6e-3";
double d = atof(s);
return 0;
}
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 ?
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.
The standard way to convert any number to a string is with
sprintf()
Code: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