2012-02-09 6 views
1

私はファイルから読み込み、すべての行の入力の一致を見つけることができるC++プログラムを作成しようとしています。すべての行は、昏睡で区切られた単一のレコードであることに注意してください。一致するものが見つかった場合、予想される出力はレコードの文字列になります。C++ファイルから読み込んでデータをトークン化

例えば

:データファイル=>

うんざりアンドリュー、アンディ、アンドリュー・アンダーソン
ヒスイ、ヒスイソニア・ブレイド

入力=>ヒスイ

出力から=>うんざり

どうすればいいですか? strtokを実装しようとしていますが、無駄です。これまでのところ、私は良い結果を得ていません。誰かがこれで私を助けてくれますか?私はそれを実行したとき、私はどこかに取得していますと思います...が、それでも出力画面がクラッシュし、この問題に関する

EDIT

。これは私のコードです

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

誰でも私のためにこれに光を当てることができますか?

EDIT ....

私はこの1つ上のいくつかの進歩を持っている...問題は今

#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

+0

良い答えを受け入れる必要がありますか? (ニックネームのように、 "姓、名"、ミドルネーム) – Dan

+0

私にプログラミングのクラスの宿題のようなにおいがします。 –

答えて

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でこれをやっている... –

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