![]() |
|
#1
|
|||
|
|||
Converting string to floatI'm working on a program that takes a bunch of valued from a .txt file, using getline. Each line is a string, and is separated into sub strings via a loop.
For example: 11 1111 111 1 111 I can get things working perfectly up to the point where it takes a line like above. It finds the first blank space, and copies every location from 0 to the number of the white space into a temporary string. Then it snips off the leading white space, and runs the loop again. When it runs, it would print out: Code:
Each time through, it snips off just what I want, and keeps going till the string is empty. CPP / C++ / C Code:
The problem that I am having (and it's driving me nuts) is that I cannot convert the string to a float... or an integer, or anything. According to my textbook (Gaddis), it's the easiest thing in the world. The syntax the book lists is just: CPP / C++ / C Code:
...but it doesn't work. I've tried making an integer/double/float and setting it equal to the string, like: CPP / C++ / C Code:
"cannot convert 'std::string' to 'const char*' for argument '1' to 'double atof(const char*)'" I've been going bonkers searching the web for how to do this, and I think maybe I'm trying to convert a dynamic variable into a static one, but I can't for the life of me find an example of some way to fix things that helps me out. From what the book shows me, I can't see why if my temp string is a string, I can't just use atof or atoi to convert it into something I can actually do math with :-? I've hit the end of my rope, and was hoping someone here might be able to help me out? P.S. Yes, I do have the <cstdlib> include file in the program |
|
#2
|
||||
|
||||
|
Quote:
So, the definition of atof looks like this: CPP / C++ / C Code:
It expects a const char * parameter, but you feed it a std::string. In order to convert it to a C-style array (char *), use the c_str() member: CPP / C++ / C Code:
Try it now! Best regards, Lucian __________________
Please read these Guidelines before posting on the forum "A person who never made a mistake never tried anything new." Einstein |
|
#3
|
|||
|
|||
|
Thank you! I had never used that before, but I looked it up, and after some trial and error, got it to work perfectly! I really appreciate your help
|
Recent GIDBlog
Python ebook by crystalattice
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| LNK2005 Error: Already defined in... | TekiFreek | C++ Forum | 11 | 05-Dec-2007 21:47 |
| Would Anyone Like to do This? | bradc0101 | C Programming Language | 0 | 30-Oct-2006 20:57 |
| Canny edge detector | Skm | Java Forum | 1 | 01-Jan-2006 07:51 |
| Help wit my source code compiler errors | Krandygrl00 | C++ Forum | 1 | 06-Jun-2005 09:14 |
Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The