2012-02-09 99 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; 
}