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:

200200125,41123,John
200200125,31054,,David
200200125,45305,Nick
200200125,44866,Smith
200200125,41024,Cathy
200200127,31525,Steve
200200127,42429,Robert
200200127,42430.,Serena
...

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

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

while(strcmp(secNum,"44923")!=0&&!inFile.eof()){
inFile.getline(ID,size,',');
inFile.getline(secNum,size,',');
inFile.getline(name,size,'\n');}............

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?

Recommended Answers

All 2 Replies

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.