how would i go about converting a string to a double?
how would i go about converting a string to a double?
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
1. Use the atof function:
2. Use stringstreams:Code:#include <iostream> #include <string> #include <cstdlib> using namespace std; int main() { string str("19.874"); double d; // Use atof to convert string to double d = atof(str.c_str()); // Output double value cout << d << endl; return 0; }
Code:#include <iostream> #include <string> #include <sstream> using namespace std; int main() { string str("19.874"); stringstream sstr(str); double d; // Extract double value from stringstream sstr >> d; // Output double value cout << d << endl; return 0; }
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
http://www.cppreference.com/stdstring/atof.html
this is how you can do it in C not C++ hope it helps
[edit1]
took me a little while to find the correct link.
if you saw this with the old link, sorry to confuse you.
here is the index to the site with good details
http://www.cppreference.com/index.html
if all else fails google it.
[/edit1]
Last edited by xviddivxoggmp3; 03-27-2005 at 02:14 PM.
"Hence to fight and conquer in all your battles is not supreme excellence;
supreme excellence consists in breaking the enemy's resistance without fighting."
Art of War Sun Tzu
thanks for that...
also how do you convert a double to a string?
using <sstream>:
Code:#include <sstream> using namespace std; string makeString(double d) { ostringstream ss; ss<<d<<flush; return ss.str(); }
Last edited by sean; 03-27-2005 at 06:30 PM. Reason: Improper Code Tag Use
here is another link i found that might be of assistance to you.
all i did again was run a search on google to find it.
it uses stringstream to convert from and to the formats your looking for.
http://pegasus.rutgers.edu/~elflord/...ingstream.html
"Hence to fight and conquer in all your battles is not supreme excellence;
supreme excellence consists in breaking the enemy's resistance without fighting."
Art of War Sun Tzu