|
-
December 15th, 2005, 11:15 AM
#1
peek() with ifstream - Now more interesting!
C'mon somebody must at least want to look at this thread......... ;-) I just need to know how to force an ifstream object back one "space" in a file.
Ah well, the title didn't update did it....
Hi,
Does peek() increment the file pointer or does it just look at the next int then decrement back to where it was before peek() was called?
To add to this:
If it does increment, which I think it does, how do I decrement back one "space". It sounds such a simple thing to want to do but I've not found how to yet.
Reason is I have a function that needs to know the value of an int before calling an overloaded >> operator for a class, but, the >> operator also needs to read this same int (it wouldn't if it was only used from this function, but it isn't.....)
Cheers.
Last edited by ggmn; December 15th, 2005 at 11:47 AM.
-
December 15th, 2005, 12:20 PM
#2
Re: peek() with ifstream
Hi,
Peek() is a member of istream.
Goole is your friend.
Jeff
-
December 15th, 2005, 01:20 PM
#3
Re: peek() with ifstream
1) peek does not increment the stream position
2) to put back the last character , you can use unget.
3) if you want to "put-back" an entire int value, the easiest
might be to save the stream position before reading the int,
then if you want to put it back, do a seekg() to that position.
see this short example:
Code:
#include <sstream>
using namespace std;
int main()
{
int i;
char c;
stringstream ss("123 456 7890 111 222");
ss >> i; // i = 123 , stream position is the space between 3 and 4
ss.get(c); // c = SPACE
c = ss.peek(); // c = 4
ss.get(c); // c = 4
ss.get(c); // c = 5;
ss.unget(); // go back one position
c = ss.peek(); // c = 5
ss >> i; // i = 56
c = ss.peek(); // c = SPACE
int pos = ss.tellg(); // get and save current position
ss >> i; // i = 7890
ss >> i; // i = 111
ss.seekg(pos); // go back to previous saved position
ss >> i; // i = 7890
return 0;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|