2015-10-03 99 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