0

Why is the last line printed twice? How can I fix the bug?

#include<iostream> #include<fstream> #include<iomanip> using namespace std; class tele { private: char name[20]; long long int num; public: void writeData(); void displayData(); }; void tele::writeData() { cout<<"Enter Name: "; cin>>name; cout<<"Phone Number: "; cin>>num; //cin.ignore(); } void tele::displayData() { cout<<setiosflags(ios::right)<<setw(10)<<name<<setiosflags(ios::right)<<setw(10)<<num<<endl; } int main() { tele cus, nus; ofstream file; file.open("number.txt", ios::app); cus.writeData(); file.write((char *)&cus, sizeof(cus)); file.close(); ifstream ifile; ifile.open("number.txt", ios::ate); ifile.seekg(0); while(ifile){ ifile.read((char *)&nus, sizeof(nus)); nus.displayData(); } }

20th Jun 2020, 8:01 AM
Prashant Pant
Prashant Pant - avatar
1 Answer
+ 1
Problem is with while(ifile). Don't you think it should be if(ifile). while(ifile){ ifile.read((char *)&nus, sizeof(nus)); nus.displayData(); }
20th Jun 2020, 9:45 AM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar