我正在尝试创建一个C++程序,该程序允许我从文件中读取并从每行中找到输入的匹配项。请注意,每行都是由昏迷分隔的单个记录。如果找到匹配项,则预期的输出将是记录中的字符串。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");
}
有人可以帮我解决这个问题吗?
您应该接受很好的答案 – zeller 2012-02-09 15:24:10
您是否需要担心逗号与领域本身? (像昵称,“姓氏,名字”,中间名) – Dan 2012-02-09 15:26:51
闻起来像编程课作业给我。 – 2012-02-09 15:27:58