从文件中连续读取

Reading consecutively from a file

本文关键字:读取 连续 文件      更新时间:2023-10-16

我有一个从文件中读取用户名和密码的程序。文件的排列方式如下:

Username
Password
Username
Password
...

我不知道如何让它每一本都读。这是我的东西。

标题:

#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
class authentication
{
  private:
         string username;
         string password;
  public:
        void authenticate();
        void change_password();            
}; 

类实现:

#include "authentication.h"
void authentication::authenticate()
{
cout << "Enter usernamen";
cin >> username;
cout << "Enter passwordn";
cin >> password;
string temp_username, temp_password;
 ifstream myfile ("user_list.txt");
 if(myfile.is_open())
 {
     getline(myfile, temp_username);
 }

}

驱动程序:

#include "authentication.h"
using namespace std;
int main(int argc, char *argv[])
{
authentication test1;
test1.authenticate();
system("PAUSE");
return EXIT_SUCCESS;
}

您的文件似乎使用普通的空格而不是换行符来辨别记录。因此,我会这样做:

struct UserDetails
{
  std::string username_;
  std::string password_;
};
std::istream& operator >> ( std::istream& is, UserDetails& details )
{
  std::string username, password;
  if( is )
  { 
    if( (is >> username) && (is >> password ) )
    { 
      details.username_ = username;
      details.password_ = password;
    } 
  }
  return is;
}
void test()
{
  std::vector<UserDetails> userDetailSeq;
  while( !file.eof() )
  {
    UserDetails details;
    if( file >> details )
      { userDetailSeq.push_back( details ); }
  }
}
#include <iostream>
#include <iomanip>
#include <fstream>
#include<vector>
using namespace std;
int main(int argc, const char * argv[]){
    ifstream input (argv[1]);
    string username, password;
    vector<std::string> userNames;
    vector<std::string> passWords;
    while(input >> username){
         userNames.push_back(username);
         input >> password;
         passWords.push_back(password);
    }
}

我没有把你所有的代码都读成T,但根据你的问题和对文件外观的说明,我会这样把你的用户名添加到一个向量,把你的密码添加到另一个向量。。。只要你的用户名或密码中不允许空白,索引现在就会对齐以关联用户名和密码

注意:您将为ifstream输入(argv[1])提供文件路径;工作。。。要在xcode中执行此操作,请转到product、scheme、edit scheme,点击加号并在文件路径中用引号键入。。。

如果您试图从文件中提取单个用户名和密码,请尝试使用operator >> (),如下所示:

myfile >> temp_username ;
myfile >> temp_password ;