2012-02-09 87 views
1

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

有人可以幫我解決這個問題嗎?

+1

您應該接受很好的答案 – zeller 2012-02-09 15:24:10

+0

您是否需要擔心逗號與領域本身? (像暱稱,「姓氏,名字」,中間名) – Dan 2012-02-09 15:26:51

+0

聞起來像編程課作業給我。 – 2012-02-09 15:27:58

回答

3

您可以使用boost tokenizer此:

#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從文件的時間來解析線。

+0

hmmmmm ....是否有可能不使用外部頭文件?其實我是在firebreath做這個... – 2012-02-09 15:29:58

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