-1

I'm trying to get value (all decimal number) from a text in c++. But I have a problem and I couldn't solve it

#include "pch.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

int main()
{
    std::ifstream infile("C:\\thefile.txt");
    float a, b;
    while (infile >> a >> b)
    {
        // process pair (a,b)
    }

    std::cout << a << " " << b;

}

thefile.txt:

34.123456789 77.987654321

When I run the above code,

a = 34.1235 
b = 77.9877

but I want

a = 34.123456789 
b = 77.987654321

what should I do?

EDIT: I don't want to print out of a and b. I just want they get the exact values.net

baybaybay
  • 1
  • 3

3 Answers3

5

You can't.

A float can only give you six (ish) decimal significant figures. The values in your file, after conversion from string, cannot be held in a float.

First, you need to switch to double, otherwise you won't even have a variable with the full numerical value.

Then, for output, be careful to specify the precision you want.

Please remain aware of the foibles of floating-point, and consider sticking with strings, depending on what you're doing with this data.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

There are two main things i see in your code.

  1. float precision is not enough for you data you need double data type.
  2. you need to set proper cout precision to get your desired output.

This code will work for you.

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

int main()
{
    std::ifstream infile("newfile.txt");
    double a, b;
    std::cout.precision(11);
    while (infile >> a >> b)
    {
        // process pair (a,b)
    }

    std::cout << a << " " << b;
}
GIRISH kuniyal
  • 740
  • 1
  • 5
  • 14
0

you should read your inputs into a string and then convert them into double (depending on enough precision in float on your computer). you can directly display strings. A possible answer is here.

string word;  
openfile >> word;
double lol = atof(word.c_str());