我如何表达我想做某事“如果函数返回 true/false”

Tyl*_*aff 1 c++ syntax boolean

我正在制作一个字典程序。在将单词添加到字典之前,AddWord 函数会调用 SearchForWord 函数,如果搜索函数发现传递给它的单词已经在字典中,则返回 true。

在添加函数中,我希望它仅在搜索函数返回 false(意味着它没有找到该单词)时才移动到实际添加单词的部分,并且我不知道如何正确表达这一点。

编辑:我从 emacs 复制并粘贴了这一切,格式很时髦,不要讨厌。

bool Dictionary:: AddAWord(string word)
{
  ofstream fout;  
  string fileName="#.txt";  
  fileName[0]=toupper(word[0]);  

  if(SearchForWord(word)=false){   //here i figured the SearchForWord function would be called and return either true or false  
    //add word  
  }else{  
    //dont add word  
  }
Run Code Online (Sandbox Code Playgroud)

如果有帮助的话,这是完整的搜索功能

bool Dictionary::SearchForWord(string word)  
{  
   ofstream fout;  
   ifstream fin;  
   string x;  
   string fileName="#.txt";  
   fileName[0]=toupper(word[0]);  
   fout.open(fileName.data());  
   if(!fin.eof()){  
     while(fin>>x){  
      if(x=word){  
       cout<<"Word found during search";  
       return(Dictionary::success);  
      }  
     }  
    }else{  
       return(Dictionary::failure);  
    }  
}
Run Code Online (Sandbox Code Playgroud)

Bil*_*ter 5

你要;

if(SearchForWord(word) == false)
Run Code Online (Sandbox Code Playgroud)

不是

if(SearchForWord(word) = false)
Run Code Online (Sandbox Code Playgroud)

从风格上来说,最好还是去;

if( !SearchForWord(word) )
Run Code Online (Sandbox Code Playgroud)

或者甚至更好;

bool word_found = SearchForWord(word);
if( !word_found )
Run Code Online (Sandbox Code Playgroud)

我发现引入这样的命名良好的布尔变量非常有用,它增强了可读性,因为在你的头脑中大声读出条件现在会导致“如果没有找到单词”。此外,在大多数调试器中跟踪进度变得更加容易且不易混淆。