C++ string to double conversion

Steelerz37

Senior member
Feb 15, 2003
693
0
0
I have to write a program for my c++ class and this one part has me stuck. It works for normal integers without decimal points but not for a double. Here is a snippet of code

balanceOwed = currentLine.substr(tempHolder1, tempHolder3);
cout << balanceOwed << endl;
recPtr[recCounter].balanceOwed = atoi(balanceOwed.c_str());

balanceOwed is a string, and currentLine is the line of an input file
the cout statement outputs the string value that I want to be in recPtr.[recCounter].balanceOwed
instead it only does up to the decimal point

ex. cout << balanceOwed; would output 12.44
but after the conversion cout << recPtr[recCounter].balanceOwed would only output 12

I have a feeling the atoi function isnt handling it correctly. Is there a better way to be doing this? I have to be using the getline() function to read my input file. If I have left out any info you may need to assist me let me know. Thanks in advance.

Ben

 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
Have you read about what atoi is supposed to do?

Learning the purpose and results of library functions is an important part of learning to program. Also, the online documentation for one library function will often include links to similar functions that might be closer to what you need.
 

Steelerz37

Senior member
Feb 15, 2003
693
0
0
doh, thanks for that...i have been sitting here for a couple hours working on this program and I hit that part and just used that code I used previously. thanks, that got me to what i needed to find :)
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
All part of the learning process -- next time you need a string-to-number conversion you'll definitely remember the difference between the atoXX functions :)
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
You could also avoid legacy C stuff and do something like:

recPtr[recCounter].balanceOwed << stringstream(balanceOwed);
 

Kntx

Platinum Member
Dec 11, 2000
2,270
0
71
doesn't the boost library have something like <lexial_cast> that does that?
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Originally posted by: Kntx
doesn't the boost library have something like <lexial_cast> that does that?

Yeah, lexical_cast. But at the end of the day it just provides a convenient wrapper around a stringstream.