c++ - Reading data from a file and storing each line in an array? -
i have file lines of integers. want read each line slot in array. have code below, not work. i'm not sure if i'm on right track.
void read_save() { ifstream in; int arr[100]; string line; in.open("file.txt"); while (in.peek() != eof) { getline(in, line, '\n'); strcpy(arr, line.c_str()); } in.clear(); in.close(); }
there several ways parse integer value out of string.
first, let's fix loop:
int pos = 0; while( std::getline(in, line) && pos < 100 ) { int value = 0; // insert chosen parsing method here arr[pos++] = value; } here non-exhaustive list of common options:
use
std::strtol// return 0 on error (indistinguishable parsing actual 0) value = std::strtol( line.c_str(), nullptr, 10 );use
std::stoi// throw exception on error value = std::stoi( line );build
std::istringstream, read it:std::istringstream iss( line ); iss >> value; if( !iss ) { // failed parse value. }use
std::sscanfif( 1 != std::sscanf( line.c_str(), "%d", &value ) ) { // failed parse value. }
now, note bounds-test on loop checking pos < 100. because array has storage limit. actually, have overridden global 1 local 1 in read_save, hiding smaller array lost when function finishes.
you can have arbitrary-sized "array" (not array) using other container types provided standard library. useful ones provide random access std::vector , std::deque. let's use vector , change definition of read_save bit more useful:
std::vector<int> read_save( std::istream & in ) { std::vector<int> values; std::string line; for( int line_number = 1; getline( in, line ); line_number++ ) { try { int value = std::stoi( line ); values.push_back( value ); } catch( std::bad_alloc & e ) { std::cerr << "error (line " << line_number << "): out of memory!" << std::endl; throw e; } catch( std::exception & e) { std::cerr << "error (line " << line_number << "): " << e.what() << std::endl; } } return values; } and finally, call becomes:
std::ifstream in( "file.txt" ); std::vector<int> values = read_save( in );
Comments
Post a Comment