Read from file line by line and parse to vector a lot of ints in c++ -
i have seen lot of similar posts regarding similar cases case bit different. i'm newbie c++, appreciated.
i have large file full of lines full of integers. each number separated blank spaces. need diferent lines stay seperate, don't want read file on 1 go. want read line line , parse each line in vector of integers. code i've got this:
int main () { string line; ifstream myfile; myfile.open ("numbers.txt"); vector<int> vec1; int const2=0; int a; while ( getline (myfile,line) ){ // understand reads line // line , stores string "line" while (line >> a){ // part 1 can't right, // want push_back every int // string vec1 doesn't work vec1.push_back(a); // more stuff } // more stuff } myfile.close(); return 0; }
here c++11 way (use -std=c++0x
g++ or clang++), can google each function don't know. using back_inserter
, istream_iterator
cleaner while/for loop come on own. using deque
in context more efficient. can take file name main input.
#include <algorithm> #include <iterator> #include <iostream> #include <sstream> #include <fstream> #include <string> #include <deque> int main() { const std::string filename = "/path/to/file.txt"; std::string line_buf; std::ifstream file( filename ); std::deque< std::deque<int> > parsed_data; if (file) while ( std::getline(file,line_buf) ) { std::deque<int> parsed_line; std::stringstream ss( line_buf ); std::copy( std::istream_iterator<int>(ss), std::istream_iterator<int>(), std::back_inserter(parsed_line) ); parsed_data.emplace_back(); parsed_data.back().swap( parsed_line ); } }
to check result in console, can use function
#include <cstdio> void show_result( const std::deque< std::deque<int> >& data ) { size_t line_count = 0; ( auto& line: data ) { printf( "line %02ld: ", ++line_count ); ( auto& num: line ) printf( "%d ", num ); printf( "\n" ); } }
Comments
Post a Comment