3

I need help with my C++ code, which reads data from an ASCII file and stores them into an std::vector<double>. The data are stored consecutively (as in the example below). For some reasons I want to substitute the while(iss>>token) with a for loop, like I did for the first while loop, when I use getline().

Here is the code and below the ASCII file example.

#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include <stdio.h>     
#include <stdlib.h>

using namespace std;

int main(int argc, char** argv){

 std::ifstream file("example_file_ASCII");
 std::vector<double> tmp_table;
 std::string line;
 
 //while(std::getline(file, line)){
 for( string line; getline( file, line ); ){
   std::istringstream iss(line);
   std::string token;

   while ((iss >> token)){
     if (some conditions)
       tmp_table.push_back(std::stod(token));
     else (other conditions)
       //jump some lines for example
     }
  }
  

}

The example_file_ASCII:

1221  91.  94.  96.  98.  100.  102.  104.  106.  108.  110.  114.  118.  121.
 125.  127.  128.  131.  132.  134.  137.  140.  143.  147.  151.  155.  159.
 162.  166.  170.  173.  177.  180.  182.  186.  191.  194.  198.  202.  205.
 //the file continues
AStopher
  • 4,207
  • 11
  • 50
  • 75
fslack
  • 189
  • 9
  • 1
    Actually, you don't need the inner loop at all: `tmp_table = std::vector(std::istream_iterator(iss), std::istream_iterator());` – Some programmer dude Nov 04 '20 at 11:05
  • Why do you want to replace a `while` loop with a `for` loop? What's the problem with `while`? BTW, no need to `getline` and to read into `string` `token` first, you can directly read into doubles from the file. – Werner Henze Nov 04 '20 at 11:08
  • To amend my first comment, you should probably use `insert` instead: `tmp_table.insert(end(tmp_table), std::istream_iterator(iss), std::istream_iterator());` – Some programmer dude Nov 04 '20 at 11:11
  • ok, thanks. I simplified the code so much, I don't need just to append elemets to the tmp_table vector, I also need to put some conditions, so I think I need the inner loop. I show you modifying the thread. – fslack Nov 04 '20 at 11:19
  • 1
    Now it makes more sense to have that loop. And you could basically copy the first `for` loop if it's what you want: `for (std::string token; iss >> token; )` – Some programmer dude Nov 04 '20 at 11:25
  • Consider the base approach of first writing a function `vector read_file(const string& filename)` and then another function `vector to_double& input)`. Not as efficient, but increases readability, can be tested separately and can be recycled in the future (for example is easier to adapt to parsing integers). – Aziuth Nov 04 '20 at 14:33

0 Answers0