Sign in to follow this  
NewbJ

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

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
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

#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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this