2015-10-03 103 views
0

我做了一個代碼,它在文本文件中找到一個單詞。代碼工作正常,但問題是我需要搜索確切的單詞是否存在,但它會給出相同的結果,即使它只是另一個單詞的一部分。 例如,我在尋找單詞「你好」,但它說已經存在,因爲txt文件中包含單詞「Hello_World」,它不是一樣的,而是包含它。 我如何檢查確切的單詞並忽略其他人。我正在考慮用這個詞的長度做些什麼,而忽略任何更長的但不確定的事情。 的代碼是在這裏:C++中的詞搜索

cout << "\n Type a word: "; 
    getline(cin, someword); 

    file.open("myfile.txt"); 

    if (file.is_open()){ 
     while (!file.eof()){ 
      getline(file, line); 
      if ((offset = line.find(someword, 0)) != string::npos){ 

       cout << "\n Word is already exist!! " << endl; 
       file.close(); 
      } 
     } 
     file.close(); 
    } 
+1

嘗試使用正則表達式而不是'find'方法 – ZivS

回答

1

使用此代碼,以分割詞和搜索意圖之一:

#include <sstream> 

stringstream ss(line); 
while (getline(ss, tmp, ' ')){ 
    if (tmp == someword){ 
     //found 
    } 
} 
+0

你是對的!我犯了一個錯誤。我會解決這個問題。抱歉。 – AKJ88

+0

此代碼假定行以目標詞開始,不包含標點符號,並且當該詞是較長詞的後綴時失敗。 –

+0

@Don Reba抱歉是粗魯,但爲什麼我有-1這個答案?! – AKJ88

2
string line; 
getline(file, line); 

vector<string> words = TextToWords(line); 
if (find(words.begin(), words.end(), someword) != words.end()) 
    cout << "\n Word already exists.\n"; 

TextToWords實現是取決於你。或者使用正則表達式庫。

+0

無法實現TextToWords – bontoo