从显示输出中最后一行详细信息的文本文件中读取两次

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

本文关键字:文件 文本 读取 两次 详细信息 显示 最后 一行 输出      更新时间:2023-10-16

这是我的文本文件(sample.txt)格式

john    123 
jim 89 
britney 852  

当我从文件中读取并输出详细信息时,它会显示最后一行两次。程序需要分别获取用户名和密码。这样比较就很容易了
这是我对上述文件的示例输出

john  123 
jim  89 
britney  852 
britney  852 

我如何克服这一点,并告诉我它在输出中显示两次的原因
提前谢谢。

代码:

#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;
}  

这是一个可以搜索的经典EOF检测问题。在StackOverflow中搜索"c++读取文件eof"。

更改:
while (!infile.eof())
收件人:
while (infile >> usern >> passwd)

EOF仅在进行读取尝试之后检测到。