• Advertisement
Sign in to follow this  

Resetting streams... (I think...)

This topic is 4947 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This came up awhile ago, but it didn't really get answered (it was just tacked onto the end of another thing)...does anyone know how to reset (I think that' what it's called) a stream, specifically a file stream? I was told I needed to do this if I was going to input the file to an int rather than a char. example:
int number;
file >> number; 
if there's a better way to do this without resetting the stream (or whatever it's called), I'd be happy to hear about those, but for what I'm doing I think I do need it to be an int. thanks!

Share this post


Link to post
Share on other sites
Advertisement
neither...the problem is actually far less complicated than that...I have a file that looks like this:

1 Question$Answer$data/images/img.bmp$
2 Qusetion2$Answer2$data/images/img2.bmp$
..etc...

I have to search for a number in the file...searching for single characters is cool...but once I get to 10, it just sees the 1 and considers the 0 part of the question...

Share this post


Link to post
Share on other sites
Ah. You have to save the position of the get pointer with ftellg(), read the number (with >>, which will read as much as it can), and then restore the position with fseekg()

Share this post


Link to post
Share on other sites
thanks...I've looked up tellg() and seekg() & what they do, but I still don't really get how that would work...could I have an example please?

Share this post


Link to post
Share on other sites

#include <fstream>
#include <string>

std::ifstream ifs("filename.txt);

int number;

while(!ifs.eof())
{
std::ifstream::pos_type checkpoint = ifs.tellg();
ifs >> number;
ifs.seekg(checkpoint);

if (number==750) // for example
{
std::string line;
std::getline(ifs, line);

// The line *will* include the number "750"
// Do stuff with the line
}
else
ifs.ignore(numeric_limits<int>::max()); // skip to the next line
}





Or is that not what you were trying to do (I didn't quite understand what you mean by 'reset')

Share this post


Link to post
Share on other sites
yeah, I wasn't sure what word to use, but I *think* that's what I want to do...basically I couldn't do it by just plain inputting because (for reasons beyond my knowledge) it would get stuck on just the first number

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement