1

My code is intended to tell the user whether the string entered is a keyword in c++. I am reading the keywords from a file into a set and then checking if the user supplied string is in it.

#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <fstream>

using namespace std;

int main()
{ 
        set<string> key;
        fstream fs;
        string b;
        fs.open("keywords.txt",fstream::in);
        while(getline(fs,b)) 
                key.insert(b);
        b.clear();

        for(auto x:key) 
                cout << x << endl;

        cout << "Enter String user\nPress exit to terminate\n";

        while(getline(cin,b))
        {
                if(b == "exit")
                        break;
                if(key.find(b) != key.end())
                        cout << "This is a keyword\n";
                else
                        cout << "This is a not a keyword\n";
                b.clear();
        }
        fs.close();
}

The keywords.txt file is just a list of keywords and can be obtained from here

The problem is that my program reads all keywords correctly but for some of them such as false,public it cannot find them in the set.

i.e. when I enter false as user input it says, "This is not a keyword."

royhowie
  • 11,075
  • 14
  • 50
  • 67

1 Answers1

6

Considering your input file, I think you have some keyword names with trailing spaces.

"catch       "
"false         "

You can trim the strings before inserting in the set to remove spaces, using boost::trim or your own trim (see this question for instance.)

(If you want some advice as for your code:

  • You can use std::ifstream like this for input file streams:

    std::ifstream file( "keywords.txt" );

  • You do not need to call .close() at then of the scope, it will be done automatically thanks to RAII.

  • You should not reuse the same std::string objects for every purpose, you can declare new string objects close to their use. You should give them better names like "line" instead of "b". Doing this, you don't need to call ".clear()" for your strings.

  • Every line has just one word, you could use while(fs>>b) the >> will ignore the spaces (from moldbinlo & wangxf comments)

)

Community
  • 1
  • 1
Nikko
  • 4,182
  • 1
  • 26
  • 44