0

This is the code:

{
 //Open and write to (virtual) memory
 if (memory)
    ofstream outFile;
    const char *outputFileName = ("memory.txt");
    outFile.open(outputFileName, ios::out);
    outFile<<input<<endl;
    outFile.close();


}

This is the error:

 |32|error: 'outFile' was not declared in this scope|

Now it appears that I did declare outFile properly but it doesn't seem that the compiler recognizes that. Either that or I'm missing something. I don't know. If anyone could please help me figure this out it would be greatly appreciated.

  • 8
    The scope of `outFile` is just within the boolean condition which is just that single line after your boolean condition, you probably wanted to enclose the full body in braces `{}` e.g. `if (memory){ ofstream outFile;......outFile.close();}` You maybe confusing indentation (from a python background) to scoping in `c++` which ignores indentation. You need to use braces `{}` if you intend to enclose more than a single statement within the scope of a boolean condition unless you're a masochist and want everything on a single line – EdChum Jul 16 '18 at 12:13
  • C++ can't be learned by guessing. Please consult [these C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Ron Jul 16 '18 at 12:15

2 Answers2

0

You are missing braces for your if ({}).

As written, the declaration is the only statement that belongs to the if, and it is gone after the if is completed:

{
  //Open and write to (virtual) memory
  if (memory)
  {
    ofstream outFile;
    const char *outputFileName = ("memory.txt");
    outFile.open(outputFileName, ios::out);
    outFile<<input<<endl;
    outFile.close();
  }
}
Aganju
  • 6,295
  • 1
  • 12
  • 23
0

The scope of an if-statement, without braces indicating scope, is the next statement (i.e. up to the next semicolon). That means outFile is only declared within the scope of the if-statement, as noted by EdChum in the comments. You likely intended to place braces around the entire block as such:

if (memory)
{
    ofstream outFile;
    const char *outputFileName = ("memory.txt");
    outFile.open(outputFileName, ios::out);
    outFile<<input<<endl;
    outFile.close();
}
Athos vk
  • 201
  • 1
  • 6
  • Thanks so much! Although with all the other if statement I have in the same file I can't believe I didn't spot this. I apologize for wasting your time. – Gh0stwarr10r Jul 16 '18 at 12:31