Advertisement
Guest User

Untitled

a guest
Nov 26th, 2014
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. // open the file for importing data
  2.         ifstream myfile("test_data.txt");
  3.         if (myfile.is_open())
  4.         {
  5.  
  6.             // eof allows all the rows of data to be converted one at a time
  7.             while (!myfile.eof())
  8.             {
  9.                 getline (myfile, bLine); // grab the immediate line as a string
  10.  
  11.                 // this next while loop converts the row at hand into individual strings, which are converted to type double.
  12.                 while (bLine.find(",", 0) != string::npos) // loop until there isn't a comma
  13.                 {
  14.                     int comma_pos = bLine.find(",", 0); // look for the comma position
  15.                     double value = atof(bLine.substr(0, comma_pos).c_str());
  16.                     temp.push_back(value);
  17.                     bLine = bLine.substr(comma_pos + 1, bLine.size() - comma_pos - 1);  //  remove the substring before the first comma
  18.                        
  19.                 }
  20.  
  21.             // the final value, which doesn't have a comma after it, hasn't been extracted
  22.             temp.push_back(atof(bLine.c_str()));
  23.             // push back temporary 1D row vector into the 2D vector
  24.             data.push_back(temp);
  25.             // add one to the rowcount
  26.             rowcount++;
  27.             // the above section will loop for each row - pushing each row's numbers to the data vector, and counting the rows
  28.             }
  29.  
  30.             // close the file after reading from it
  31.             cout << "There are " << rowcount << " rows in the CSV file.\n";
  32.             myfile.close();
  33.  
  34.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement