fern17
fern17

Reputation: 487

How to read float number with more digits in C++?

I'm having issues when I try to read a float number from a file. I need to read 3 float numbers given in a line like this:
v -30.50889491515995 -31.95820181187489 0
(I'm doing a parser from a .obj file from Rhinoceros)

Here is my code (before this I read a string to see if is a 'v'):

fstream f(name.c_str());  
...  
f>>p.x>>p.y>>p.z;  

name is a string readed before from standard input.
P is a struct:

typedef struct Point{  
double x;  
double y;  
double z;  
}Point;  

The problem is that the data readed is:
-30.5089 -31.9582 0
instead of
-30.50889491515995 -31.95820181187489 0
It rounds at 4 decimals, and I don't want that!

I tried to read with fscanf but I can't send it a fstream object. Something like this:

fscanf(f,"%f %f %f",p.x,p.y,p.z);

I also tried this, but it didn't work:

f>>setprecision(10)>>fixed>>p.x>>p.y>>p.z;

Any ideas of how to avoid this? I need more precision in the vertex coordinates!

Thank you very much.

Upvotes: 2

Views: 1267

Answers (2)

Tony Delroy
Tony Delroy

Reputation: 106196

C++ always inputs the numbers with full precision, but you need to specify the precision for display (i.e. when outputting the values):

#include <iostream>
#include <iomanip>
#include <sstream>

int main()
{
    std::istringstream iss("30.50889491515995 -31.95820181187489 0");

    float x, y, z;

    if (iss >> x >> y >> z)
        std::cout << std::setprecision(10) << std::fixed
                  << x << ' ' << y << ' ' << z << '\n';
}

output:

30.5088939667 -31.9582023621 0.0000000000

Upvotes: 4

Tristan
Tristan

Reputation: 916

setprecision should do what you are wanting to do. You said it didn't work--what did you get out of it?

Did you try running it in a debugger? Is it possible that it is not being input properly?

Upvotes: 0

Related Questions