2013-10-16 27 views
2

好吧,所以我試圖將加密文本寫入文件。錯誤:'myfile'未在此範圍內聲明

由於某種原因,我得到一個未在此範圍內聲明的編譯錯誤。

這是我的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中,並且完美運行。但是當我嘗試它時,我得到了錯誤。這很奇怪,因爲我包括在內。

+0

您是否可以將您的代碼和信息降低到仍然存在此特定錯誤的必要最小值?您提供的大部分信息都不相關,只是減少了問題。也就是說,這個錯誤是不言自明的。 –

+0

除了你還沒有聲明'myfile',你在'output [i] + x'處出現了數組訪問'i == 0 – Sergey

+0

@Shafik Yaghmour我添加了這行,而是得到相同的錯誤,但告訴我是流沒有在此範圍內聲明。 – Crju

回答

4

您錯過了任何語言的基本知識......您的myfile定義在哪裏?

+0

@Polentino myfile屬於。這不是一個變量。這裏的示例中使用的確切代碼與http://www.cplusplus.com/doc/tutorial/files/中使用的文件名相同。 – Crju

+1

'ofstream myfile;':直接從示例中獲取 – Paddyd

+1

@Syd不,它不。是的,這是一個變量。不,它的代碼不一樣。 – alternative

7

你沒有申報,也沒有定義您的myfile

所以它不會在目前的情況下存在,這就是爲什麼你收到此錯誤

你已經錯過了這部分代碼ofstream myfile;

+1

由於他的代碼很幸運地沒有'using namespace std;',所以你不需要'std ::'。 –

+1

註冊成功!是的,我已經測試過,你需要設置'使用命名空間標準;'到*。h全局範圍的頭文件。別忘了添加#include #include 。 –

3

首先,你需要使用ofstream,所以做using namespace std;

然後聲明你的myfile對象:ofstream myfile;

一般經驗法則:標準庫永遠不會包含一個以'my'爲前綴的變量,您只需使用而不用聲明。