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

This is a discussion on Create a text file: "undeclared identifier" Error using If-statement within the C++ Programming forums, part of the General Programming Boards category; Hi folks, this is my first time here. Great site, I gained a great deal from the tutorials! I have ...

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    1

    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.
    Code:
    do
    {
    cout<<"Create textfile (y/n) ?";
    getline(cin,createdatafile);
    }
    while(createdatafile!="y" && createdatafile!="n");
    
    if(createdatafile=="y")
      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?

    Thanks,
    Zahid

  2. #2
    Software Developer jverkoey's Avatar
    Join Date
    Feb 2003
    Location
    University of Waterloo
    Posts
    1,904
    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:
    Code:
    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, 01:09 AM
  2. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 04:39 AM
  3. Simple File encryption
    By caroundw5h in forum C Programming
    Replies: 2
    Last Post: 10-13-2004, 11:51 PM
  4. Removing text between /* */ in a file
    By 0rion in forum C Programming
    Replies: 2
    Last Post: 04-05-2004, 09: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, 12:45 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21