I'm trying to make a dictionary with 2-character words but not so much success Here's my code:
#include <cstdlib>
#include <iostream>
#include <map>
using namespace std;
int main(int argc, char *argv[]){
map<char*,int> m;
//input 5 two-lengthed words
for (int i=0;i<5;i++){
char s[3];
cin>>s;
s[2] = '\0';
m[s]=1; //add a key
}
//checking if a word exists.
cout<<"Word you want to check whether it exists:"<<endl;
char chck[3];
cin>>chck;
chck[2]='\0';
//I heard this is how you check whether a key exists:
bool exists = m.find(chck)==m.end();
cout<<((exists)?"Yes!":"No.")<<endl;
system("pause"); //Yea, system, I know.
return 0;
}
Whenever I enter the words, and then when I want to check whether a word is in a dictionary, I always get printed "No."?
I come from Java so I got used to references, not pointers, so that's where I'm probably wrong. I want to learn how to properly use the maps so can you please what am I supposed to do here?
Thanks
//I heard this is how you check whether a key exists:
bool exists = m.find(chck)==m.end();
Yes, but the condition is true if the element does not exist. You should call your vaviable notExists
:
bool notExists = m.find(chck)==m.end();
Now, if all you want to do is check if a work exists, you can use an std::set<std::string>
. If you want the word to be a key to something else, then you need std::map<std::string, SomeThingElse>
.
Forget about those char*
. Use std::string
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With