string - Reading from file in C++, dealing with blanks -
i tying read text file in c++98. has pattern, field empty:
id name grade level 1 80 2 b b 3 c 90
how can read file such can ignore blanks? ( wish use regex: \d*)
is there simple way of doing that?
you need use knowledge have input make assumptions missing. can use std::stringstream
parse individual terms text line. in other words std::stringstream
deals blanks ignoring spaces , getting complete term only, example std::stringstream("aaa bbb") >> >> b
load strings a
"aaa"
, b
"bbb"
.
here example program parses input, making robust parser scratch can difficult, if input strict , know expect can away simple code:
#include <iostream> #include <fstream> #include <string> #include <sstream> //----------------------------------------------------------------------------- // holds data entry struct entry { int id; std::string name; int grade; std::string level; entry() { // default values, if missing. id = 0; name = "unknown"; grade = 0; level = "?"; } void parsefromstream( std::stringstream &line ) { std::string s; line >> s; if( s[0] >= '0' && s[0] <= '9' ) { // number, id. id = atoi( s.c_str() ); // next term if( line.eof() ) return; line >> s; } if( s[0] >= 'a' && s[0] <= 'z' || s[0] >= 'a' && s[0] <= 'z' ) { // letter, name name = s; // next term if( line.eof() ) return; line >> s; } if( s[0] >= '0' && s[0] <= '9' ) { // number, grade grade = atoi( s.c_str() ); // next term if( line.eof() ) return; line >> s; } // last term, must level level = s; } }; //----------------------------------------------------------------------------- int main(void) { std::ifstream input( "test.txt" ); std::string line; std::getline( input, line ); // (ignore text header) while( !input.eof() ) { entry entry; std::getline( input, line ); // skip header if( line == "" ) continue; // skip empty lines. entry.parsefromstream( std::stringstream( line )); std::cout << entry.id << ' ' << entry.name << ' ' << entry.grade << ' ' << entry.level << std::endl; } return 0; }
Comments
Post a Comment