【问题标题】:Error: 'myfile' was not declared in this scope错误:未在此范围内声明“myfile”
【发布时间】:2013-10-24 15:30:38
【问题描述】:

好的,我正在尝试将加密文本写入文件。

由于某种原因,我收到一个未在此范围内声明的编译错误。

这是我的 encryption.cpp 文件:

#include <iostream>
#include <fstream>
#include <string>

class encrypt{
    public:
        static void cryptText(std::string newpass)
        {
            int x = newpass.size();

            int output[x -1];

            for(int i = 0; i <= x -1; i++)
            {
                output[i] = (int)newpass[i];
                std::cout << char(output[i] + x);
                //Here I am trying to write output onto the file. For some reason, though,
                //I get the error.
                myfile.open ("passwords.thaddeus");
                myfile << output << std::endl;
                myfile.close();

            }

            std::cout << std::endl;

        }

};

我查看了 cplusplus.com 文件中的输入/输出文档。我将他们的示例程序复制到 Code::Blocks 中,它运行良好。但是当我尝试它时,我得到了错误。这很奇怪,因为我包括了。

【问题讨论】:

  • 您能否将您的代码和信息减少到仍然显示此特定错误的必要最小值?您提供的大多数信息都不相关,只会影响问题。也就是说,这个错误是不言自明的。
  • 除了你没有声明 myfile 你在output[i]+x 使用 i == 0 超出了数组访问范围
  • @Shafik Yaghmour 我添加了这一行,但得到了同样的错误,但告诉我 ofstream 没有在这个范围内声明。
  • @Syd 是的,即 b/c 样本也有 using namespace std;,这很糟糕,所以如果没有,你需要做 std::ofstream myfile;

标签: c++ file input


【解决方案1】:

您既没有声明也没有定义您的 myfile 变量。

因此,它在当前上下文中不存在,这就是您收到此错误的原因。

你错过了这部分代码ofstream myfile;

【讨论】:

  • 您缺少对 std:: 的需求,因为谢天谢地他的代码没有 using namespace std;
  • 投了赞成票!是的,我已经测试过了,您需要将 using namespace std; 设置为 *.h 头文件的全局范围。不要忘记添加#include #include
【解决方案2】:

你错过了任何语言的基本知识......你的myfile 定义在哪里?

【讨论】:

  • @Polentino myfile 属于 。它不是一个变量。它实际上与此处示例中使用的完全相同的代码:cplusplus.com/doc/tutorial/files 更改了文件名。
  • ofstream myfile; :直接取自该示例
  • @Syd 不,它没有。是的,它是一个变量。不,它的代码不一样。
  • @Syd 因为他们定义了它。 ofstream myfile;
  • @Syd using namespace std;
【解决方案3】:

首先,你需要使用ofstreamusing namespace std;也是如此

然后声明您的myfile 对象:ofstream myfile;

一般经验法则:标准库从不包含以“my”为前缀的变量,供您在不声明的情况下使用。

【讨论】:

    猜你喜欢
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 2015-06-23
    • 2010-10-02
    相关资源
    最近更新 更多