c++ - Reading from a text file that shows the last line details twice in the output -


this question has answer here:

here text file (sample.txt) format

john    123  jim 89  britney 852   

when read file , output details, display last line twice. program needs take user name , password separately. comparison easy.
sample output above file

john  123  jim  89  britney  852  britney  852  

how can overcome , give me reason shows twice in output.
in advance.

the code:

#include <iostream> #include <fstream> #include <string> using namespace std; int main() {   string passwd;   string usern;   string password;   string username;   ifstream infile;   string line;   infile.open("sample.txt");   if(!infile)   {     cerr << "error during opening of file" << endl;   }   else   {     while (!infile.eof())     {       infile >> usern >> passwd ;       cout << usern << " " << passwd << endl;     }   }   cout << "enter user name : ";   cin >> username;   if (usern == username)   {     cout << "already exist" << endl;   }   infile.close();   return 0; }   

this classic eof detection issue can search for. search stackoverflow "c++ read file eof".

change:
while (!infile.eof())
to:
while (infile >> usern >> passwd)

eof detected after read attempt made.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -