c++ - 异常处理和范围

标签 c++ exception scope

所以我必须为一个刽子手游戏编写这段代码,我得到了一个 dicitonary.txt 文件,其中包含 127k 个单词,每个单词单独一行。我所做的是使用 map<int, set<string>> DICTIONARY;根据字母数存储单词。所以我这里有这段代码,但我有几个问题:

#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;
}

但我得到的是一个错误,指出 DICTIONARY 未在该范围内定义。我知道 if(){} 里有什么等等留在里面,这叫做作用域。但是我应该如何访问该 map ?

我假设有一个指针,但仍然不知道如何在范围内使用它。

如果有人也可以告诉我如何在 if 中使用 127.. 而不是小于 i 的声明我可以使用 while不是文件结尾或类似的东西?

错误输出为:

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

非常感谢您!

最佳答案

map<int, set<string>>直到 C++11 才在语法上符合 C++。错误 'DICTIONARY' was not declared in this scope是误导,原因是编译器不接受 map<int, set<string>> DICTIONARY作为变量声明,并没有将 DICTIONARY 添加到标识符表中。

将其替换为 map<int, set<string> > (注意添加的空格)

... 或者如果编译器支持,请尝试将您的代码编译为 C++11。 C++11 对 C++ 进行了重大改进!

关于c++ - 异常处理和范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22622862/

相关文章:

java - 多捕获异常处理程序中的顺序

c++ - 用不同的字符串(UVa 272 - Tex 引号)替换打开和关闭的代码不起作用

c++ - 为什么 Vector 不排序?

java - DAO 模式中的异常与返回码

java - 遍历 try/catch block ?

c++ - 线程池的 lambda 函数内部的编译器错误变量 "Not captured"

javascript - 在循环中声明的变量和重新使用的变量会发生什么

不同 block 中的 C++ 变量

c++ - -fsanitize 在 GCC-6.1 中不使用黄金链接器

java - "is unique"Eclipse UML 代表什么?