Home > OS >  Issues reading floats from .txt file
Issues reading floats from .txt file

Time:01-21

I am trying to read a .txt file with some floats into my code. I wrote a sample code just to tackle the issue outside my main code and I am using the following floats to test it:

10.8f  
100.8f
-10.8f

The issue I am running into is that the code only reads in the first float properly and displays it but all the other floats following it do not look correct:

10.8
0
4.57874e-41

Code:

#include<fstream>                                                     
#include<iostream>                                                    
#include <vector>                                                     
#include <string>                                                     
#include <iomanip>                                                    
using namespace std; 

int main()                                                            
{                                                                                                                       
  float Cam1,Cam2,Cam3;                                               
                                                                      
  string path = "sample.txt"; //Text file with above mentioned floats                                        
  ifstream fin;                                                       
                                                                      
  fin.open(path);                                                     
  if(fin.is_open())                                                   
    {                                                                                                              
      fin >> Cam1;                                                    
      fin >> Cam2;                                                    
      fin >> Cam3;                                                    
      fin.close();                                                    
    }                                                                 
                                                                      
  cout << Cam1 << '\n';                                               
  cout << Cam2 << '\n';                                               
  cout << Cam3 << '\n';                                               
}                                                                     

I really am confused as to why it reads the first properly but not the others, it works when I change the values as well, the above is just one example case. I am fairly new to C so any help would be greatly appreciated thank you!

CodePudding user response:

The f suffix is valid in C code, but not in input text parsed by istream. It's useful in code to distinguish between float and double constants, but user input doesn't control variable data types.

  •  Tags:  
  • Related