Search code examples
c++filevectorifstreamfgets

How to read entire stream of integers from fgets and push back into 1D vector?


Hello I am using c++ and i read the file using fgets, i am using while loop and sscanf to push back to my vector double while i would like to do it using a single line, like in case of ifstream but i dont want to use get line.

%% My stream of data
  151  150  149  148  147  146  145  144  143  143  141  139  138  137  135 
  132  130  130  129  128  127  127  128  129  130  129  128  127  126  127 
  127  127  127  128  128  128  129  130  130  131  131  132  132  133  133 

%% My code
vector<double> vec_TEC1D;
double temp_holder = 0.0;

while(!feof(fileptr))
    {
      fgets(line, LENGTH_LINE, fileptr);
      .....
      while(strstr(line, '\n') != NULL){
                  sscanf(line, "%lf", &temp_holder);
                  vec_TEC1D.push_back(temp_holder);
              }
      }     

I am already using 2 while loop outside the above one for other purposes, hence i would like to avoid this..

Thank you for your help!! :) Priya


Solution

  • Here are some pointers that may help you:

    So your code may look like:

    #include <algorithm>
    #include <fstream>
    #include <iostream>
    #include <iterator>
    #include <sstream>
    #include <string>
    #include <vector>
    
    
    int main(int argc, char* argv[]) {
      if(argc < 2)
        return -1;
    
      std::ifstream input(argv[1]);
      std::vector<double> data;
      std::string line;
      while(std::getline(input, line)) {
        std::stringstream converter(line);
        std::copy(std::istream_iterator<double>(converter),
              std::istream_iterator<double>(),
              std::back_inserter(data));
      }
    
      // Do something with the data, like print it...
      std::copy(begin(data), end(data), std::ostream_iterator<double>(std::cout, " "));
      return 0;
    }
    

    There are even more concise way of doing this, but I propose to process each line separatley as you do in your code. Maybe your file contains other lines and you want to process these differently.