Solved

# string to double

Posted on 2004-11-28
498 Views
I am trying to read a file one line at a time  ,tokenize a string with space delimiter. Then convert the lines to objects.

the lines in the file are in this format

A 100000.12  0.08 11
S 100000.12  0.08 11

now I am trying to read this file and tokenize  them with space delimiter so that I can create objects from them.

while(getline(ins, line)){

stringstream ss(line);
if(ss >> buff)
{
if(buff == "A")
{
//(double prin, double rate, int length)
//ss.setw(10);
ss>>principal;
ss>>rate;

What is Interesting is that though both principal and rate are declared as double. it is not reading the values like 10000.12 or 100000.12 .  it is taking out the single digit or both the digits after the decimal depending on the size of the number.  what is the problem here.

0
Question by:ashokpappu

LVL 55

Expert Comment

you must declare buff as 'char' type. Something like this:

char buff;

while(getline(ins, line)){

stringstream ss(line);
if(ss >> buff)
{
if(buff == 'A')    //   <--------single quotes here
{
//(double prin, double rate, int length)
//ss.setw(10);
ss>>principal;
0

Author Comment

THe problem is not in the Buff  the problem is in the principal.  it it not reading double values  properly
0

LVL 55

Accepted Solution

Are you sure you have an input problem. I think it is an output problem. Have a look to this example:

int main()
{
string buff, line = "A 100000.12 0.08 11";
float principal, rate;

stringstream ss(line);

if(ss >> buff) {
if(buff == "A")
{
ss >> principal >> rate;
}
}

cout.precision(10);            // IF YOU DONT PUT THIS LINE, THEN principal VALUE WILL BE CUTTED AT ***OUTPUT TIME****
cout << buff << endl;
cout << principal << endl;     // BUT INTERNALLY IT HAS STORED VALUE CORRECTLY
cout << rate << endl;

system("pause");

return 0;

}
0

## Featured Post

### Suggested Solutions

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.