Thread: Create a text file: "undeclared identifier" Error using If-statement

  1. #1
    Registered User
    Join Date
    Aug 2007

    Create a text file: "undeclared identifier" Error using If-statement

    Hi folks, this is my first time here. Great site, I gained a great deal from the tutorials! I have looked everywhere for a solution to my problem, hopefully you guys will be able to help.

    Basically my program prompts the user whether or not they would like to save the session as a text file.
    cout<<"Create textfile (y/n) ?";
    while(createdatafile!="y" && createdatafile!="n");
      ofstream datafile ("datafile.txt");
    Now if that if-statement is there, the program will give me an error:
    error C2065: 'datafile': undeclared identifier

    When that if statement is not there (aka will always create a txt file) it works perfectly (as in it creates the text file).

    How do I make it so I can control whether or not it creates a text file?


  2. #2
    Software Developer jverkoey's Avatar
    Join Date
    Feb 2003
    New York
    The problem here is scope. By not explicitly declaring the scope* of the if statement, C++ is implicitly creating one for you. As a result your ofstream variable is going out of scope immediately after it's created.

    Seeing as we don't know what the rest of your code looks like, your options are to declare the ofstream outside of the if's scope (i.e. immediately before) or to enclose all of your logging code in that particular if statement.

    * Example of explicitly declaring the scope:
    if (x)
    {  // Start new scope
      int x;  // <- Only visible in this scope
    }  // End new scope
    x = 5;  // Compiler error

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Deleting / Changing a record in a text file
    By clearrtc in forum C Programming
    Replies: 9
    Last Post: 08-21-2006, 12:09 AM
  2. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM
  3. Simple File encryption
    By caroundw5h in forum C Programming
    Replies: 2
    Last Post: 10-13-2004, 10:51 PM
  4. Removing text between /* */ in a file
    By 0rion in forum C Programming
    Replies: 2
    Last Post: 04-05-2004, 08:54 AM
  5. Read word from text file (It is an essay)
    By forfor in forum C Programming
    Replies: 7
    Last Post: 05-08-2003, 11:45 AM