0

I'm trying to read data from a file line by line and push them back to a vector The data is of the format 123 23 45 19 46 22 87 26 31

The program gives no output and an error code of 11.

std::vector<int>* readDataFromFile(std::string path){


    std::vector<int>* v = new std::vector<int>;
    int a, b, c;
    std::ifstream inputStream;
    inputStream.open(path);
    while(inputStream>>a>>b){
        v->push_back(a);
        v->push_back(b);
        v->push_back(c);
    }
    inputStream.close();

}

int main() {

    std::vector<int>* v = readDataFromFile("file1.txt");
    for(auto it= v->begin(); it != v->end(); it++){
        std::cout<<*it<<std::endl;
    }

    return 0;
}
Antithesis
  • 327
  • 2
  • 4
  • 17

1 Answers1

2
  1. Don't forget to read c in the loop:

    while(inputStream>>a>>b>>c) {
        v->push_back(a);
        v->push_back(b);
        v->push_back(c);
    }
    
  2. You are allocating a std::vector dynamically and never deleting it. Instead return the vector by value.

  3. And also the call to fstream::close is not necessary, the stream is closed from fstream's destructor when it goes out of scope.

  4. In general it is better to pass read-only string parameters by const reference.

    #include <iostream>
    #include <fstream>
    #include <vector>
    
    std::vector<int> readDataFromFile(const std::string& path){
      std::vector<int> v;
      int a, b, c;
      std::ifstream inputStream(path);
      while(inputStream>>a>>b>>c){
          v.push_back(a);
          v.push_back(b);
          v.push_back(c);
      }
    
      return v;
    }
    
    int main() {
      std::vector<int> v = readDataFromFile("file1.txt");
      for(auto it = v.begin(); it != v.end(); it++){
          std::cout<<*it<<std::endl;
      }
    
      return 0;
    }
    
  • It is worth noting that returning an `std::vector` by value may copy the entire vector, depending on the optimizations the compiler is able to perform. – Jørgen Fogh Oct 27 '15 at 14:47
  • This is true, but it is a common practice to return vectors by value and rely on RVO (or in C++11 move semantics). See this question: https://stackoverflow.com/questions/11247654/returning-stdvector-by-value – Simón González Guerra Oct 27 '15 at 14:58