-2

Here is my text file (sample.txt) format

john    123 
jim 89 
britney 852  

When I read from a file and output the details, it display the last line twice. The program needs to take user name and password separately. So then comparison will be easy.
This is my sample output for the above file

john  123 
jim  89 
britney  852 
britney  852 

How can I overcome this and also give me the reason it shows twice in the output.
thanks 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 the 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;
}  
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
triblocker
  • 33
  • 1
  • 1
  • 4
  • 2
    how about showing us the code? Should we guess it? – Chris Maes Apr 14 '14 at 14:17
  • 1
    Please share the code, without your code nobody can check whats wrong. – Flovdis Apr 14 '14 at 14:17
  • #include #include #include 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 the 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; } – triblocker Apr 14 '14 at 14:40
  • I have tried to post the code. But format cannot get corrected – triblocker Apr 14 '14 at 14:40

1 Answers1

1

This is a classic EOF detection issue that you can search for. Search StackOverflow for "c++ read file eof".

Change:
while (!infile.eof())
To:
while (infile >> usern >> passwd)

EOF is only detected after a read attempt is made.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154