简体   繁体   中英

Reading floating point numbers from text file and copying to a vector of floating point numbers

I need to make a code in c++ that reads floating point numbers from a text file separated by commas and copies to a vector of floating point numbers .The text file contains several thousands of floating point integers seperated by a comma ( like 1, 1, 69.8, 110, 0, -1.8, -1.8, 0, 120, 0, 0, 0, 0, 3.23,).I tried using getline() , but i guess it is meant to read text file as strings, and save in a vector of strings , not floating point numbers.Can any one help me with this

The following code is not working in the way i expected

vector<float> ReplayBuffer;
ifstream in;
in.open("fileName.txt");
if(in.is_open())
{
    in.setf(ios::fixed);
    in.precision(3);

   in.seekg(0,ios::end);
   fileSizes = in.tellg();

   in.seekg(0,ios::beg);
   float number = 0;
   for(int i = 0; i<fileSizes/sizeof(float);i++)
   {
    getline(in, ReplayBuffer[i],', ');
   }

   for(int i = 0;i<ReplayBuffer.size();i++)
    {  cout<<ReplayBuffer[i]<<" , "<<endl; }
   in.close();
    }
}

The simplest way is perhaps

for (std::string f; getline(in, f, ',');)
  ReplayBuffer.push_back(std::stof(f));

You'll need to wrap it in a try - catch block if there's any chance the floats in the file are invalid.

Your code can then be simplified to something like

vector<float> ReplayBuffer;
ifstream in("fileName.txt");

for (std::string f; getline(in, f, ',');)
  ReplayBuffer.push_back(std::stof(f));

for (auto f : ReplayBuffer)
  std::cout << f << " , ";

fixed and precision only affects output (unless you are using a custom num_get facet), even if you were to keep your original code those two lines do nothing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM