c++ - Simple read a double array from file -


i have double numbers in file (one on each line) trying read c++ array. using below code, below error while running:

segmentation fault: 11

#include <iostream> #include <fstream> #include <string> #include <vector> using namespace std;  int main () {     string line;     ifstream myfile ("temp2.csv");     std::vector<double> myarray;     int index = 0;     if (myfile.is_open())     {         while (! myfile.eof() )         {             getline (myfile,line);             cout << line << endl; //            myarray[index++] << line;             myarray[index++] = atoi( line.c_str() );         }         myfile.close();     }      else cout << "unable open file";      return 0; } 

you can't

myarray[index++] = atoi( line.c_str() ); 

it empty vector. either need push_back elements it. or initialize sufficient memory.

this should work:

#include <iostream> #include <fstream> #include <string> #include <vector> #include <stdlib.h> using namespace std;  int main () {     string line;     ifstream myfile ("temp2.csv");     std::vector<double> myarray;     int index = 0;     if (myfile.is_open())     {         while (! myfile.eof() )         {             getline (myfile,line);             cout << line << endl; //            myarray[index++] << line;             myarray.push_back(atoi( line.c_str() ));         }         myfile.close();     }      else cout << "unable open file";      return 0; } 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -