Get string from input file until integer?
Nov 21, 2013 at 1:24am UTC
One of my input files which looks like this:
1 2 3 4 5 6 7 8 9
Stroustrup, Bjarne 8 8 -1 -1 -1
Lovelace, Ada 1 60 14 43 -1
von Neumann, Jon 77 48 65 -1 -1
Wirth, Niklaus 51 59 -1 -1 -1
Wozniak, Steve 81 -1 -1 -1 -1
Babbage, Charles 31 92 -1 -1 -1
Hopper, Grace 76 -1 -1 -1 -1
Bird, Tweety -99 -99 -99 -99 -99
Sylvester 77 39 -1 -1 -1
Currently my program streams the data in using
infile >> lastName >> firstName >> ...
Unfortunately this only worked with the other input files because every line actually had a last and first name. Here, because of the two part last name in the third line and only the first name in the last line, the rest of the data fails to stream. Is there any method to grab a string from the beginning of the line until it reaches an integer?
Nov 21, 2013 at 2:01am UTC
how about :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
// if you don't know how many elements you will read
std::vector<std::string> name( 5 ); // we allocate 5 initially to prevent excess push_back()'s
std::vector<int > col1( 5 );
std::vector<int > col2( 5 );
std::vector<int > col3( 5 );
std::vector<int > col4( 5 );
std::vector<int > col5( 5 );
std::string tempLastname;
std::string tempFirstName;
int ntemp;
while ( getline( infile, tempLastName, ',' ) ) { //http://www.cplusplus.com/reference/string/string/getline/
//-- read name, store in name vector
infile >> tempFirstName;
name.push_back( tempLastName + ', ' + tempFirstName ); // append
//-- read first num
infile >> ntemp;
col1.push_back( ntemp );
//-- read sec
infile >> ntemp;
col2.push_back( ntemp );
//-- 3rd
infile >> ntemp;
col3.push_back( ntemp );
//-- 4th
infile >> ntemp;
col4.push_back( ntemp );
//-- 5th
infile >> ntemp;
col5.push_back( ntemp );
infile.ignore();
}
remember to
#include <string>
and
#include <vector>
Last edited on Nov 21, 2013 at 9:59am UTC
Topic archived. No new replies allowed.