从文件中连续读取

时间:2013-12-03 20:48:00

标签: c++ file-io filestream

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

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 username\n";
cin >> username;
cout << "Enter password\n";
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;
}

3 个答案:

答案 0 :(得分:1)

#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中执行此操作,转到产品,方案,编辑方案,点击加号并在引号中键入文件的路径...

答案 1 :(得分:1)

您的文件似乎使用普通的空格而不是换行来识别记录。所以我会做这样的事情:

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

答案 2 :(得分:0)

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

myfile >> temp_username ;
myfile >> temp_password ;
相关问题