Skip to main content
gamedev.net
🔒 Locked

Go away eof!

Started by Orikal Oct 9, 2001 at 2:44 PM 4 replies 400+ views
Original Post
Orikal
Orikal
I need to check and see if a user-entered number is in a file. My TA said to do it like this: int IDnumber; int IDcheck; while (IDnumber != 0) { in_stream.open("input.txt"); cout << "Enter ID number (0 to exit): "; cin >> IDnumber; //exit loop upon recieving zero if (IDnumber == 0) break; while (! in_stream.eof()) { in_stream >> IDcheck; if (IDcheck == IDnumber) cout << "YES it''s there."; break; } in_stream.close(); } If the number they entered is in the file, the loop continues, closes and reopens the file, and sets the cursor back at the beginning upon reopening. The only problem is that if the number isn''t there (and thus in_stream.eof() returns true), when the loop restarts and reopens the file, the cursor is still at the end of the file. Is there a way I can put it back at the beginning (and/or a better way than closing and reopening it)? Thanx
Big B
Big B
Assuming you are using std::ifstream

  
int IDnumber;
int IDcheck;
in_stream.open("input.txt");

while (IDnumber != 0)
{
in_stream.seekg(0); //back to beginning of file

cout << "Enter ID number (0 to exit): ";
cin >> IDnumber;

//exit loop upon recieving zero

if (IDnumber == 0)
break;

while (! in_stream.eof())
{
in_stream >> IDcheck;

if (IDcheck == IDnumber)
cout << "YES it''s there.";
break;
}

}
in_stream.close();


VolkerG
VolkerG
in_stream.seekg (0);
will jump to the beginning of your stream (file).
Orikal
Orikal
You guys kick ass. One more question: Is there any way to do it without seekg?
jwalker
jwalker
dont think so .
for simple IO, there is rewind() and fseek()

but for ifstream i dont think there is rewind.

seekg() will do fine ..



{ Stating the obvious never helped any situation !! }
Orikal
Orikal
Shit. seekg isn''t working. Could you show me the code for the entire program? I''m using Codewarrior 6.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.