2016-05-18 8 views
0

は、私は現在、テキストファイルから一度に1つの単語を読むためにこれを使用しています:C++テキストファイルからフレーズを読むにはどうすればよいですか?

int Dictionary::processFile(string file) { //receives a text file name to be read from user 
    string word; 
    int wordCount = 0; 

    ifstream fin; 
    fin.open(file.c_str()); 
    if (fin.fail()) { 
     cout << endl; 
     cout << "Input file opening failed.\n"; 
     return 0; 
    } 

    while (fin >> word) { 
     word = trimString(word); //trimString removes any symbols including spaces and words. only reads words. 
     exTree.ExtAvlTree_processNode(word); //processNode simply inserts the word into an avl tree. irrelevant to the question 
     wordCount++; 
    } 
    fin.close(); 
    return wordCount; 
} 

は、どのように私はそれは言葉を処理する前に、一度に2-3の言葉を読むことができるように変更することができます。例えば、単語を読み込んでそれを処理した後、同じ単語を読み込みますが、次の隣接する単語を追加して、それがフレーズ(2ワードからなる)になると同じ2ワードを読み込みますが、次の3ワードを別のフレーズに追加します。

余分な質問、上記の場合はacheiveableです:

iはスペースを削除から機能をtrimStringどのように停止することができますし、シンボルだけを削除しますか?

これは、トリム文字列関数です:

string Dictionary::trimString(string input){ 
    stringstream ss; 
    for (int x = 0; x < (int) input.size(); x++) { 
     if(isalpha(input[x])){ 
      ss << input[x]; 
     } 
    } 

    if (ss.str().length() > 0) { 
     return ss.str(); 
    } else { 
     return ""; 
    } 
} 
+0

を分離シンボルを削除しますか? " - >はもはやスペースシンボルではありませんか? – ForceBru

+0

@ForceBruどうすれば免除できますか? – nanjero05

+0

*「トリムストリング関数がスペースを削除するのを止めてシンボルを削除するにはどうすればいいですか?」* ... 'fin >> word'は抽出を停止するためのデリミネーターとしてスペースを使用しません。だから、なぜそれが何もないときに単語のスペースをチェックしたいのですか? –

答えて

0

あなたは、あなたはあなたが説明した方法でそれらを使用するforループを使用することができ、あなたがSTDに読み出された各単語::ベクトルを追加することができます。以下のコードは、あなたが例で

vector<string> words; 
    string word = ""; 
    ifstream infile("words.txt", ios::in); 

    while (infile >> word) 
    { 
    /* 
    you can process each word here like removing commas, periods 
    and such(if that is in fact what you want) before you add 
    them to the vector 
    */ 
    words.push_back(word); 
    } 

    string phrase = ""; 

    for (int k = 0; k < words.size(); k++) 
    { 
    phrase += " " + words[k]; 
    cout << phrase << endl; 
    } 

を行うことができ、何かの例ですが、私はあなたがフレーズ内の単語はスペースになりたいと仮定し、私はスペースのみを削除から機能をtrimString停止とすることができますどのように」

関連する問題