Click to See Complete Forum and Search --> : string conversion
scottincz
July 16th, 2002, 02:58 PM
Hi gang
I have a file that contains floating point numbers in text like this
-0.321435435D-02
0.4324325435D-02
1.4343243434D+00
2.4343434343D+5
-0.432432443D+2
etc
etc
i need to be able to loop through the file and convert each line ot a double where d-xx is the . placement
for example
0.4324325435D-02 = 0.004324325435
and
-0.432432443D+2 = -043.2432443
any tips on achieving this.
Thanks in advance
Scott
Alexey B
July 16th, 2002, 03:08 PM
Originally posted by MSDN:
double atof( const char *string );
The string argument to atof has the following form:
[whitespace] [sign] [digits] [.digits] [ {d | D | e | E }[sign]digits]That should help you.
Philip Nicoletti
July 16th, 2002, 03:09 PM
standard C++ i/o should take care of this.
(following code not tested ...)
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream in("input.txt");
if (!in)
{
cout << "could not open file" << endl;
return 1;
}
double d;
while (in >> d && !in.fail())
{
cout << "read from file : " << d << endl;
}
return 0;
}
scottincz
July 16th, 2002, 03:14 PM
You missed the point. I can read each line of text from the file but i need to convert the string format of a double (non standard) to a double.
thanks
Scott
Alexey B
July 16th, 2002, 03:19 PM
The atof function does just that. The format of your string corresponds to the format that the function accepts, so using it should be an easy task. Check MSDN for more information on atof.
Meijian An
July 16th, 2002, 04:45 PM
...
char ss[256];
while(...)
{
//read double d from your file.
sprintf(ss,"%f",d);
cout<<<ss<<endl;
//or use cout.width(..) and cout.setf(..)
...
}
cup
July 16th, 2002, 05:31 PM
Are you just mixing up external and internal representations of the same number? If you read 0.4324325435D-02 and printf it in f format, you will get 0.004324325435. If you printf it in E format, you will get 0.4324325435E-02. Those are just external fomats. Internally, the number is the same.
jfaust
July 16th, 2002, 05:40 PM
I think you're confused where I was confused.
0.4324325435D-02 is a legal format for a double value.
Jeff
Paul McKenzie
July 16th, 2002, 07:51 PM
Originally posted by scottincz
You missed the point. I can read each line of text from the file but i need to convert the string format of a double (non standard) to a double.
thanks
Scott There is another standard function besides atof() and that is strtod(). Either one should work for you.
Regards,
Paul McKenzie
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.