stream - C++: reading data from an external file; problem with my code for stopping read before end of file -
to use code have written performing calculations, need read in data (numbers , strings) external text file , store them in vectors of either strings or ints/doubles. have written template function doing this. cashcow, howard hinnant, , wilhelmtell kindly helped previous problem.
the function seems work fine ints/doubles, have problem string data.
i need data 1 line of external file go vector, function reads in multiple lines. here's mean. let's in external text file (below):
vectorone // identifier subset of data 1 vector
'1' '2' '3' // these values should go 1 vector, (vectorone)
vectortwo // identifier subset of data vector (vectortwo)
'4' '5' '6' // these values should go different vector
vectorthree // identifier subset of data vector (vectorthree)
'7' '8' '9' // these values should go different vector
if data subset identifier/label (like vectorone), want data on next line go result vector. problem data below identifier/label ending in result vector. if vectortwo want, expect result vector contain elements, "4, 5, 6." intead, contains 4 9. in code (below), thought line:
while ( file.get() != '\n' );
ensured read stop @ newline (i.e., after each line of data).
i grateful suggestions going wrong.
here's code (for clarity, configured strings):
#include <algorithm> #include <cctype> #include <istream> #include <fstream> #include <iostream> #include <vector> #include <string> #include <sstream> #include <iterator> using namespace std; template<typename t> void fileread( std::vector<t>& results, const std::string& thefile, const std::string& findme, t& temp ) { std::ifstream file( thefile.c_str() ); std::string line; while( std::getline( file, line ) ) { if( line == findme ) { do{ std::getline( file, line, '\'' ); std::getline( file, line, '\''); std::istringstream mystream( line ); mystream >> temp; results.push_back( temp ); } while ( file.get() != '\n' ); } } } int main () { const std::string thefile = "test.txt"; // path file const std::string findme = "labelinfile"; std::string temp; std::vector<string> results; fileread<std::string>( results, thefile, findme, temp ); cout << "result: \n"; std::copy(results.begin(), results.end(), std::ostream_iterator<string>(std::cout, "\n")); return 0; }
thanks
looks me may have problem mixing getline
, get
.
when you've read name of vector want, start reading parts between single quotes. once you've read whatever between single quotes, check see if next character end of line. if there's else on line before newline, test fails , reads whatever between next pair of single quotes. if there's comment @ end of line, or space, or @ past last single quote, you've got fail.
try reading whole line string, , reading stringstream. way, can't go past end of line.
Comments
Post a Comment