incorrect output of stof() function

May 14, 2019 at 5:05pm
I wrote a program to read lines from file, which has few float numbers written on it, length of decimals is 6 to 7 , but when converted to float using stof() length of decimal reduces to 4, I cross checked with string parameter of stof() ,it was correct , output written at end of code,
my question is how to make stof return full decimal value to string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(){
    ifstream testfile;
    string line;
    float lat,lng;
    testfile.open("testfile.txt");
    if (!testfile) {
        cout << "Unable to open file";
        exit(1); // terminate with error
    }
char ch;
    getline(testfile,line);
    getline(testfile,line);//read 2 lines


 while (!testfile.eof())
        {
        getline(testfile,line,' ');
        getline(testfile,line,' ');
        lat=stof(line);
        cout<<lat<<" "<<line<<endl;
        
        break;
        }
        testfile.close(); // Step 5: Closing file


return 0;
}


output
20.2783 20.2783121
May 14, 2019 at 5:27pm
std::cout only outputs up to 6 digits by default.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <iomanip>
#include <string>

int main()
{
	std::string line = "20.2783121";
	float lat = std::stof(line);
	std::cout << std::fixed << std::setprecision(7); 
	std::cout << "lat:  " << lat  << '\n';
	std::cout << "line: " << line << '\n';
}
lat:  20.2783127
line: 20.2783121

The reason the last digit is not outputted correctly is because float doesn't have enough precision. Use double and std::stod if you want better precision.
Last edited on May 14, 2019 at 5:29pm
May 14, 2019 at 5:31pm
First why are you using getline() instead of directly reading the floating point numbers?

Second there is no problem with the stof(), the problem is with how you are attempting to print the number. You need to tell the operator<< that you want to print more decimals by using std::setprecision().


May 14, 2019 at 6:16pm
Please do not tell people to stop using getline() when dealing with user input.

OP is correct to extract by line, then parse the line.
May 14, 2019 at 9:50pm
Why?

I can understand your point for more complicated code but for basic code there is nothing wrong with skipping the string and going straight into a numeric variable. Also just using getline() is not the whole ball of wax, you still need to handle data errors.

Topic archived. No new replies allowed.