0

for an assignment I wrote a program and we hit start without debugging to use the program and the console would ask questions and such. As part of this assignment, we have to write everything that appears in the console window (in visual studio, when we hit start without debugging or ctrl+f5) to a .txt file. Is there a way to have every cout statement write to this file or do I have to type it out on every line that i want to be written to the .txt?

using the ofstream with #include fstream for this by the way

  • 1) "Everything that appears in the console window" includes your input; do you need to write it as well? It'll complicate the matters a lot. 2) Do you have to do this in your program? For this I always use [tee](https://en.wikipedia.org/wiki/Tee_(command)). –  Oct 01 '19 at 02:58
  • 1) yes, we also have to include the input that the "user" of the program would type. 2. yes, we have to write everything that would appear in the console window to a .txt. – Adam Keller Oct 01 '19 at 02:59
  • (Disclaimer: I never did this, so I may be unaware of some issues). If you have to do this in the code, you can define your own class for which you define `operator <<`, so that it prints to both console and file. This way there will be no duplication. –  Oct 01 '19 at 03:02
  • hmm.. sorry i am really new to coding i just started a few weeks ago. if you are able to, would you be willing to give me an example of what i would write and where i should put it? thanks for your help though! – Adam Keller Oct 01 '19 at 03:04
  • I think this example may help to understand how `ostream` and `operator <<` work: https://learn.microsoft.com/en-us/cpp/standard-library/overloading-the-output-operator-for-your-own-classes?view=vs-2019. Think about it this way: you want to print something to both console and file, so you should define a function which does it (something like `template void print(T output) { cout << output; fout << output; }`). It should already work (so maybe it's enough for you), but to match the standard stream syntax, you can define your own class and your own `operator <<`. –  Oct 01 '19 at 03:12
  • thank you for your help dyukha! i will look into it. – Adam Keller Oct 01 '19 at 03:15
  • Possible duplicate of [How to redirect cin and cout to files?](https://stackoverflow.com/questions/10150468/how-to-redirect-cin-and-cout-to-files) – David C. Rankin Oct 01 '19 at 03:55

0 Answers0