C++ question re: reading input from a file

OK, I’m a C++ newbie, but I’m trying to learn.
I have a question. I just finished reading a file using ifstream, and now I want to read it again (code snippet below). I thought I could reset to the beginning of the file by using the seekg( 0 ) method. This doesn’t appear to work.

Does anyone have any suggestions or comments?



  // read in a file of phrases.
  tfile.seekg(0);                       // reset data file;
  while (!tfile.eof())                  // loop as long as there are items left
  {
    tfile.getline(buffer, 49);          // get an item from the file
    if (!tfile.eof())
        phrases.push_back(buffer);
  }//end of while loop


You might need to call the stream’s clear method after encountering an error. (Reaching the end-of-file counts as an error.)

See some more discussion in section 9.3.4 of this page.

You are calling seekg incorrectly. The absolute position (one parameter) form is only appropriate with values obtained from tellg. Instead you want to use the relative position form (two parameters). Specifically:


tfile.seekg(0,std::ios::beg);

You can also position relative to the current location (std::ios::cur) or the end (std::ios::end).

Thanks, I’ll give it a shot. I like that tutorial BTW. It’s bookmarked now.

E3

Oh, I get it! When I was reading the manual on the two forms, I didn’t understand what beg, cur, end meant :smack: . Now it seems so simple.

My work around was just to create a second vector when I created the first, but I still hated not knowing why I couldn’t get it to work.

Thanks, everybody.

E3