gEdringer
gEdringer

Reputation: 16583

Exception Handling and Scope

So I have to write this code for a hangman game, and I am supplied with a dicitonary.txt file which contain 127k words each on a separate line. What I did is I used a map<int, set<string>> DICTIONARY; to store words based on their letter count. So I have this code here but I have few issues:

#include <iostream>
#include <map>
#include <set>
#include <cmath>
#include <string>
#include <fstream>

using namespace std;

int main(){
   map<int, set<string>> DICTIONARY;

   try{
      ifstream file("dictionary.txt");
      if(file.is_open()){
           string TEMP_INPUT;
           for(int i = 0; i < 127143; i++){
               file >> TEMP_INPUT;

               DICTIONARY[TEMP_INPUT.length()].insert(TEMP_INPUT);
           }
      }
      else throw 404;
   }catch(int x){
         cout << "Error: " << x << " - file not found!" << endl;
   }

   return 0;
}

But what I get is an error saying that DICTIONARY was not defined in that scope. I know that what is in the if(){} etc. stays in it, it's called scope. But how should I access that map?

I assume a pointer but still don't know how to use it in the scope.

And if someone could also show me how instead of using the 127.. in the if statement for less than i I can use a while not end of file or something similar?

The error output is:

source.cpp In function 'int main()':
source.cpp:14:24: error: 'DICTIONARY' was not declared in this scope
source.cpp:14:21: error: '>>' should be '> >' within a nested template argument list

Thank you very much in advance!

Upvotes: 0

Views: 274

Answers (1)

Jo So
Jo So

Reputation: 26501

map<int, set<string>> wasn't syntactically conforming C++ until C++11. The error 'DICTIONARY' was not declared in this scope is misleading, the reason is that the compiler didn't accept map<int, set<string>> DICTIONARY as a variable declaration, and didn't add DICTIONARY to the identifier table.

Replace that with map<int, set<string> > (note the added whitespace)

... Or try to compile your code as C++11 if the compiler supports that. C++11 brings major improvements to C++!

Upvotes: 1

Related Questions