Emilio Garcia Emilio Garcia - 2 months ago 14
C++ Question

Writing output to text file doesn't show input

I have a C++ program that is supposed to read input from a text file, and write the output to a text file. I wanted to try an achieve this without adding any extra code, so in the command line I write

project.exe<input.txt>output.txt


This works, but in the ouput.txt file, I can't see any of the input. It just says something like:

Enter option:
option output


I could just add
std::cout<<option;
after every input, but is there a way to show the input without adding any extra code?

Answer

You're trying to find a way to make the Windows shell copy or clone your input stream so that, after it is consumed by your program, it is also sent to the output stream. There are some problems with that:

  1. It was consumed by your program!
  2. Your program has control of the output stream

I'm not saying it's impossible (on Linux, some concoction with tee may be possible), but if it's possible then it's going to be hacky and certainly unconventional.

Frankly I would stick with your own idea of just mirroring the input to the output stream, within the program itself. If someone uses your program interactively then that's going to look strange for them, but you could provide a command-line switch to toggle this functionality. It would be analogous to PuTTY's optional "local echo" feature, for example.