2009-03-07 8 views
0

Это касается другого вопроса, который я задал, хотя это его собственный вопрос полностью.ofstream error

при компиляции я получаю две ошибки:

1> \ asst4.cpp (73):. Ошибка C2065: 'выходной_файл':. Необъявленный идентификатор

1> \ asst4.cpp (73) : ошибка C2228: слева от '.close' должен быть класс/struct/union

Я немного смущен относительно того, что я сделал неправильно здесь? Любые рекомендации или идеи? (Фактическое выходной_файл находится в верхней части кода

Вот полный код:.!

#include<iostream> 
#include<fstream> //used for reading/writing to files. 
#include<string> //needed for the filename. 
#include<stdio.h> //for goto statement 

using namespace std; 

int main() 
{ 
    string start; 
    char choice; 
    char letter; 
    int x; 
    int y; 
    int z; 
    string filename; 
    int garbage = rand()%('!' - '~' + 1); 
    cout << "Would you like to encrypt or decrypt a file? Please type enc, dec, or stop (case sensitive): " ; 
    cin >> start; 
    while(start == "enc") 
    { 
     x = 1; 
     y = 1; 
     cout << "How many garbage characters would you like between each correct character?: " ; 
     cin >> z; 
     cout << endl << "Please insert the name of the document you wish to encrypt, make sure you enter the name, and the file type (ie: filename.txt): " ; 
     cin >> filename; 
     ifstream infile(filename.c_str()); 
     while(!infile.eof()) 
     { 
      ofstream outfile("encrypted.txt", ios::out); 
      infile.get(letter); 
      if (x == y)   
       { 
       outfile << garbage; 
       x++;    
      } 
      else 
      { 
       if((x - y) == z)    
       { 
        outfile << letter;   
        y = x;     
       } 
       else       
       {       
        outfile << garbage; 
        x++; 
       } 
      } 
     } 
     cout << endl << "Encryption complete...please return to directory of program, a new file named encrypted.txt will be there." << endl; 
     infile.close(); 
     outfile.close(); 
     cout << "Do you wish to try again? Please press y then enter if yes (case sensitive)."; 
     cin >> choice; 
     if(choice == 'y') 
     { 
      start = "enc"; 
     } 
     else 
     { 
      cout << endl << "Do you wish to decrypt a file? Please press y then enter if yes (case sensitive)."; 
      if(choice = 'y') 
      { 
       start == "dec"; 
      } 
      else 
      { 
       start == "no"; 
      } 
     } 
    } 
    while(start == "dec") 
    { 

     //lets user choose whether to do another document or not. 
     //used to track each character in the document. 
     x = 1; //first counter for tracking correct letter. 
     y = 1; //second counter (1 is used instead of 0 for ease of reading, 1 being the "first character"). 
       //third counter (used as a check to see if the first two counters are equal). 
     //allows for user to input the filename they wish to use. 
     cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ; 
     cin >> filename; //getline(cin, filename); 
     cout << endl; 
     cout << "'Every nth character is good', what number is n?: "; 
     cin >> z; //user inputs the number at which the character is good. IE: every 5th character is good, they would input 5. 
     cout << endl; 
     z = z - 1; //by subtracting 1, you now have the number of characters you will be skipping, the one after those is the letter you want. 
     ifstream infile(filename.c_str()); //gets the filename provided, see below for incorrect input. 
     if(infile.is_open()) //checks to see if the file is opened. 
     { 
      while(!infile.eof()) //continues looping until the end of the file. 
      { 
        infile.get(letter); //gets the letters in the order that that they are in the file. 
        if (x == y)   //checks to see if the counters match... 
        { 
         x++;    //...if they do, adds 1 to the x counter. 
        } 
        else 
        { 
         if((x - y) == z)   //for every nth character that is good, x - y = nth - 1. 
         { 
          cout << letter;   //...if they don't, that means that character is one you want, so it prints that character. 
          y = x;     //sets both counters equal to restart the process of counting. 
         } 
         else      //only used when more than every other letter is garbage, continues adding 1 to the first 
         {       //counter until the first and second counters are equal. 
          x++; 
         } 
        } 
      } 
      cout << endl << "Decryption complete...please return to directory of program, a new file named encrypted.txt will be there." << endl; 
      infile.close(); 
      cout << "Do you wish to try again? Please press y then enter if yes (case sensitive)."; 
      cin >> choice; 
      if(choice == 'y') 
      { 
       start == "dec"; 
      } 
      else 
       { 
       cout << endl << "Do you wish to encrypt a file? Please press y then enter if yes (case sensitive)."; 
       if(choice == 'y') 
       { 
        start == "enc"; 
       } 
       else 
       { 
        start == "no"; 
       } 
      } 
     } 
     else //this prints out and program is skipped in case an incorrect file name is used. 
     { 
      cout << "Unable to open file, please make sure the filename is correct and that you typed in the extension" << endl; 
      cout << "IE:" << "  filename.txt" << endl; 
      cout << "You input: " << filename << endl; 
      cout << "Do you wish to try again? Please press y then enter if yes (case senstive)." ; 
      cin >> choice; 
      if(choice == 'y') 
      { 
       start == "dec"; 
      } 
      else 
      { 
       start == "no"; 
      } 
     } 
     getchar(); //because I use visual C++ express. 
    } 
} 

Благодаря загодя Джефф

ответ

2

Scoping вопрос Вы объявляете выходной_файл в ваше время. цикл, но пытаются получить доступ к нему вне указанного в то время как петля.

Move ofstream outfile("encrypted.txt", ios::out); линии сразу после ifstream infile(filename.c_str()); что перед вашим while(!infile.eof()).

+0

, который сделал это, теперь есть реальная ошибка в логике, которую я имею, где-то она решила не печатать в файл ... и минуту назад во время ее запуска, когда я остановил ее, потому что она, казалось, замерзла и открылась txt-файл, мне действительно удалось получить блокнот, чтобы сбой, указать на меня! – Jeff

+0

И как всегда, спасибо за помощь! – Jeff

0

У вас есть два варианта - как упоминается X-istence, причина, по которой ваш вызов outfile.close() не скомпилирован, заключается в том, что объект 'outfile' не существует в той же области, что и объявление outfile.

Вы можете либо переместить линию


ofstream outfile("encrypted.txt", ios::out); 

вне цикла в то время, так что подчиняется тем же правилам областей видимости, как INFILE, или вы можете переместить вызов outfile.close(); внутри цикла while, который переместит его в текущую область, в которой существует внешний файл.

Мое предпочтение состояло в том, чтобы переместить объявление outfile за цикл while, поскольку открытие файла - довольно дорогостоящая операция, и вы действительно не хотите делать это для каждой буквы, которую вы читаете из infile. Откройте его один раз, закройте его, когда-то, путь в этом случае.

Смежные вопросы