0

I need help with tellg(). I have pasted the code and where I need help.

#include<iostream> #include<fstream> #include<iomanip> #include<string> using namespace std; class Item { string name; int code; int cost; public: void getData(); void putData(); }; void Item::getData() { cout<<"Enter Item Code: "; cin>>code; cin.ignore(); cout<<"Enter Item Name: "; cin>>name; cin.ignore(); cout<<"Enter Item Cost: "; cin>>cost; cin.ignore(); } void Item::putData() { cout<<setiosflags(ios::left)<<setw(10)<<code <<setw(10)<<name <<setw(10)<<cost<<endl; } int main() { Item it[2], out; //two objects of item class. fstream file; file.open("item.txt", ios::in | ios::out | ios::trunc); for(int i=0; i<2; i++) { it[i].getData(); file.write(reinterpret_cast<char *>(&it[i]), sizeof(Item)); } file.seekg(0); cout<<setiosflags(ios::left)<<setw(10)<<"Code"<<setw(10) <<"Name" << setw(10) <<"Cost"<<endl; while(true) { file.read(reinterpret_cast<char *>(&out), sizeof(Item)); if(file.eof()) { break; } out.putData(); } file.seekg(0); //Everything works fine above this. In fact, if I were to remove "file.read" code, everything works as expected below too, the tellg() used below returns the right position; but if I include the code, it returns -1 and -1. Why???? And How can I resolve this? //My question starts from here. int pos1=file.tellg(); //I am pretty sure the compiler is confused here, there two objects "it" and "out", and the file pointer doesn't know where to direct. file.seekg(0, ios::end); //I want to know the end. int pos2=file.tellg(); cout<<"\n\nPos1 and Pos2: "<<pos1<<" "<<pos2<<endl; //This gives me -1 and -1 as answers. file.close(); }

2nd Aug 2020, 5:05 AM
Prashant Pant
Prashant Pant - avatar
1 Odpowiedź
0
I found the answer. I am supposed to use file.clear() below this code while(true) { file.read(reinterpret_cast<char *>(&out), sizeof(Item)); if(file.eof()) { break; } out.putData(); } file.clear(); //added this This got the answer. I read something like "Eof Flag off" --I couldn't understand this. What I understood was, when EOF is called, it adds something to the file that the file is no more available for anything, file.clear() removes that "flag". I would love an explanation.
2nd Aug 2020, 6:14 AM
Prashant Pant
Prashant Pant - avatar