Reputation: 5032
I am making a dictionary program. Before adding a word to the dictionary, the AddWord function calls the SearchForWord function, if the search functions discovers that the word passed to it is already in the dictionary it returns true.
In the add function I want it to move on to the part where it actually adds the word only if the search function returns false (meaning it did not find the word) and I can't figure out how to express this correctly.
Edit: I copied and pasted this all from emacs and the formatting is funky, don't hate.
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
}
Here's the full search function if it helps
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);
}
}
Upvotes: 1
Views: 10970
Reputation: 6297
You want;
if(SearchForWord(word) == false)
not
if(SearchForWord(word) = false)
As a point of style it would be better to go;
if( !SearchForWord(word) )
Or maybe even better;
bool word_found = SearchForWord(word);
if( !word_found )
I find it really useful to introduce well named boolean variables like that, it enhances readability because reading the conditional out loud in your head now results in "if not word found". Additionally it becomes easier and less confusing to trace progress within most debuggers.
Upvotes: 5
Reputation: 13426
=
is the assignment operator. It is used to assign a value to a variable(like a=5
).To check if a
is equal to b
you have to write a==b
.
So
if(SearchForWord(word)=false)
should be changed to
if(SearchForWord(word)==false)
Upvotes: 0
Reputation: 5848
You want to do: if(!SearchForWord(word))
Using = is assignment not boolean.
Upvotes: 0
Reputation: 13612
if (!SearchForWord(word)) {
// add the word
} else {
// don't add the word
}
Upvotes: 1
Reputation: 82579
You want:
if(!SearchForWord(word))
Never use ==
when comparing boolean values. You may accidentally assign the value like you are there. Consider this:
if(engagedInNuclearWar = true) { // typo. should be ==
fireMissiles();
}
Now, when this fires, the first thing it will do, because there's only ONE equals sign, is assign engagedInNuclearWar
to be true. This is a mistake, we want to be checking not assigning. As a result, we're firing missiles when we shouldn't. Some intern will probably lose his job over that (if he doesn't get killed in the nuclear holocaust that follows.)
Instead, avoid using == but rely on boolean evaluation.
if(engagedInNuclearWar) { // no chance for = vs == typo
fireMissiles();
}
Upvotes: 2