0

I have tried running this code in my school and it works like a charm but when I got home, this piece of code suddenly gets error. Can somebody enlighten me about what happened to my code? Is there something that I should correct or add in my code? edited : There were build errors in the code.

#include <iostream>
#include <fstream>
#include <string>

ofstream fileObject;

using namespace std;

int main() {
    string username[5];
    cout << "Enter username: ";
    for (int i = 0; i < 5; i++) {
        getline(cin, username[i]);
    }
    fileObject.open("open.txt", ios::app);
    for (int x = 0; x < 5; x++) {
        fileObject << username[x] << endl;
    }
    fileObject.close();
    return 0;
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
thermoplay
  • 75
  • 8
  • 7
    You get *what* errors? Build errors? Run-time errors? Unexpected results? Please refresh [ask] as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Feb 13 '20 at 15:06
  • 3
    I highly doubt that this code compiled using any common and modern C++ compiler... – dtell Feb 13 '20 at 15:08
  • 3
    As a probable hint: Think about the *order* in which you do things. For example, when you define the `fileObject` variable, does there exist a class `ofstream` in the global namespace? Perhaps you should take a step back, and think about what the `using namespace std;` line means (which [you shouldn't really have](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)). – Some programmer dude Feb 13 '20 at 15:08
  • 5
    If you get build errors, *always* include them inside the question body. Copy-pasted (as text!) in full and complete. Also add comments in the code where you get the errors. – Some programmer dude Feb 13 '20 at 15:09
  • 1
    I bet you have TurboC++ at school. Please confirm. Or: are you sure the code that works at school is actually the code you show here? – Jabberwocky Feb 13 '20 at 15:13
  • 1
    It should not have worked like a charm. It should not have worked at all. There's a mystery there. – Eljay Feb 13 '20 at 16:54
  • 1
    Don't "fix" the code in the question! It makes any answer worthless, and your question won't have any problems anymore. It's enough to mark an answer as accepted. Remember that this site isn't only for you right now, but for future programmers with similar or the same problem as well. – Some programmer dude Feb 14 '20 at 06:59

1 Answers1

3

ofstream fileObject; is above using namespace std, so it's not recongnized as a type.

Either move it below using namespace std, or use std scope, std::ofstream fileObject.

The second option is a better one, read Why is “using namespace std;” considered bad practice?

I don't see how this can run in any C++ compiler, unless you include headers that already recognize std namespace.

anastaciu
  • 23,467
  • 7
  • 28
  • 53