我正在嘗試創建一個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