i can use seekg and seekp functions to jump around differnt locations in the file with offset.
But now the txt file is written like:


i wanna serch a lines with its second numer 44923 and get its first number.

the way i used:
char ID,secNum,name;


it turns out work anyway. however,i dont like it becuase there would be too many assignments in the loop if there are more sections in every line. i just wanna skip the other sections in each line. apparently i can not use "seekg" function because the lenths of names are different. so how can i do that in a smart way?

Don't bother to save stuff you don't want. For example, if you only want the first and fifth items in a ten-item line:

string line;  // we'll read whole lines at a time

while (inFile) {
  // get a whole line
  getline( inFile, line );

  // skip blank lines
  if (line.empty()) continue;

  stringstream ss( line );  // stream to parse the line
  string first;
  string fifth;

  // get the first elt
  getline( ss, first, ',' );

  // skip elts 2..4
  for (int i = 1; i < 4; i++)
    if (!ss.ignore( 50, ',' )) {
      cout << "The line has less than ten elements" << endl;
      continue;  // next line

  // get the fifth elt
  getline( ss, fifth, ',' );

  // Show the user what we've got
  cout << "The first and fifth elements are "
       << first << " and " << fifth << endl;

How exactly you handle things like blank or misformatted lines is up to you. Also, I just used a maximum 'skip' value of 50. You might want to use something larger or smaller as appropriate.

Hope this helps.

This article has been dead for over six months. Start a new discussion instead.