Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ string to double conversion

Usually when I write anything in C++ and I need to convert a char into an int I simply make a new int equal to the char.

I used the code(snippet)

 string word;    openfile >> word;  double lol=word; 

I receive the error that

Code1.cpp cannot convert `std::string' to `double' in initialization  

What does the error mean exactly? The first word is the number 50. Thanks :)

like image 802
TimeCoder Avatar asked Jan 20 '11 23:01

TimeCoder


People also ask

What is strtod in C?

The strtod() is a builtin function in C and C++ STL which interprets the contents of the string as a floating point number and return its value as a double. It sets a pointer to point to the first character after the last valid character of the string, only if there is any, otherwise it sets the pointer to null.

Can char convert to double?

The C library function double strtod(const char *str, char **endptr) converts the string pointed to by the argument str to a floating-point number (type double). If endptr is not NULL, a pointer to the character after the last character used in the conversion is stored in the location referenced by endptr.

What does atof do in C?

Description. The atof() function converts a character string to a double-precision floating-point value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.


1 Answers

You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.

With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)

#include <stdlib.h>  int main() {     string word;       openfile >> word;     double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*                                      previously (the function requires it)*/     return 0; } 
like image 167
0x77D Avatar answered Oct 05 '22 22:10

0x77D