读取文件并标记数据以与C++中的输入进行比较

read file and tokenize data to compare to input in C++

本文关键字:输入 比较 C++ 文件 数据 读取      更新时间:2023-10-16

你能帮我吗。。我试图实现的是,当用户输入他/她的用户名和密码时,我的程序将打开一个文件,该文件存储按行排列的用户信息(用户名、密码、文件夹名、用户全名)。我有这个代码,但我似乎看不出问题。当输入应该有第一行的结果时,它会得到它。但当它解析第二行时,它就会崩溃。有人能帮我吗?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
main () {
//  string toks[]; 
  char oneline[80],*del;
  string line, creds[3], username, password;
  int x = 0;
  cout<<"Enter Username: ";
  cin>>username;
  cout<<"Enter Password: ";
  cin>>password;
  ifstream myfile;
   myfile.open("jake.txt");
  if (myfile.is_open())
  {
    while (!myfile.eof())
    {
     getline(myfile,line);
     strcpy(oneline,line.c_str());
     del = strtok(oneline,",");
     while(del!=NULL)
     {
     creds[x] = del;
     del = strtok(NULL,",");
     ++x;
     }
     if((creds[0]==username)&&(creds[1]==password))
        {
         cout<<creds[2]<<endl;
         break;
         }
    }
    myfile.close();
  }
  else 
  cout << "Unable to open file"; 
  system("pause");
}

您可能溢出了oneline缓冲区。不要使用固定大小,只需使用std::string,就像您对其他变量所做的那样。即

string oneline;
...
oneline = line;
...

并使用boost标记器在逗号上进行拆分,而不是strtok

编辑:示例用法,改编自boost docs

#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>
int tokenizer_main(int, char **){
   using namespace std;
   using namespace boost;
   string s = "This,is,a,test";
   tokenizer<> tok(s);
   for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg){
       cout << *beg << "n";
   }
}

输出

This
is
a
test