-1

I've simply put the line to print to the file inside a for loop in order print it five times yet nothing is being printed. My code is as follows:

int main() {  
    ofstream (fileAccess);  
    fileAccess.open ("fileName.txt", ofstream::app);  
    for (int i; i < 5; i++) {  
        fileAccess << "Hello World!";  
    }  
    fileAccess.close();  
}

Please help

starball
  • 20,030
  • 7
  • 43
  • 238
OsumDagN
  • 7
  • 1
  • 5
    Typo? `for (int i; ...` `i` is uninitialized . – Richard Critten Sep 10 '22 at 18:35
  • Does `fileName.txt` exist? – Yksisarvinen Sep 10 '22 at 18:38
  • Side note: The line `fileAccess.close();` is unnecessary, because the file will be closed automatically when the destructor is called. – Andreas Wenzel Sep 10 '22 at 18:55
  • Have you decided not to [run this code in your debugger](https://stackoverflow.com/questions/25385173)? I imagine you would have solved this problem in seconds. – Drew Dormann Sep 10 '22 at 19:24
  • Have you tried running your code line-by-line in a debugger while monitoring the values of all variables, in order to determine in which line your program stops behaving as intended? If you did not try this, then you may want to read this: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/12149471) You may also want to read this: [How to debug small programs?](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Andreas Wenzel Sep 10 '22 at 20:31

1 Answers1

0

Thanks to Richard Critten, I just had to initialize int i as 0. I've never had this issue before as it usually sets it to 0 by default but I changed that and it worked first try.

OsumDagN
  • 7
  • 1
  • 2
    _"it usually sets it to 0 by default"_ This is not correct. It is not set to 0 by default, it is _uninitialized_ and reading the value of an uninitialized int is always Undefined Behavior. What you have observed when reading an uninitialized int has always been Undefined Behavior, even if you currently like the behavior. – Drew Dormann Sep 10 '22 at 19:35
  • 3
    For future reference, compiling with warnings (`-Wall` in gcc) will warn you about things like this. – Silvio Mayolo Sep 10 '22 at 19:44