C++从文件中读取并标记数据

C++ read from file and tokenize data

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

我正在尝试创建一个C++程序,该程序允许我从文件中读取并从每一行中找到匹配的输入。请注意,每一行都是由昏迷分隔的单个记录。如果找到了匹配项,则预期输出将是记录中的字符串。

例如:文件中的数据=>

安德鲁,安迪,安德鲁安德森
翡翠,翡翠索尼娅刀锋

输入=>翡翠

输出=>疲惫的

我该怎么做?我正在尝试实现strtok,但没有成功。到目前为止,我没有得到好的结果。有人能帮我做这个吗?

编辑

关于这个问题,我想我已经有所进展了。。。但当我运行它时,输出屏幕仍然崩溃。这是我的代码

    #include <iostream>
#include <fstream>
#include <string>
using namespace std;
main () {
//  string toks[]; 
  char oneline[80],*del;
  string line, creds[4];
  int x = 0;
  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++;
     }
    }
    myfile.close();
 }
  else 
  cout << "Unable to open file"; 
  system("pause");
}

有人能帮我解释一下吗?

编辑。。。。

我在这方面有一些进展。。。现在的问题是,当输入与下一行匹配时,它会崩溃。。。

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

有人能帮我做这个吗?

您可以使用boost令牌化器进行以下操作:

#include <boost/tokenizer.hpp>
typedef boost::char_separator<char> separator_type;
boost::tokenizer<separator_type> tokenizer(my_text, separator_type(","));
auto it = tokenizer.begin();
while(it != tokenizer.end())
{
  std::cout << "token: " << *it++ << std::endl;
}

另请参阅getline以一次解析文件中的一行。

int main ()
{
    ifstream file("file.txt");
    string line;
    while (getline(file, line))
    {
        stringstream linestream(line);
        string item;
        while (getline(linestream, item, ','))
        {
            std::cout <<  item << endl;
        }
    }    
    return 0;
}