Input Redirection
Background
When you run a program from the command line, it can read input from the keyboard (standard input) and write output to the terminal (standard output). However, sometimes you may want to provide input to your program from a file instead of typing it manually. This is especially useful for testing programs that require a lot of input data.
Input/Output redirection is a capability many terminal shells (the program the runs the terminal, like PowerShell or Bash) provide to change the source of input and destination of output for programs.
Here we will cover just how to use input redirection to feed input to your program from a file. For deeper coverage of this topic, see Input/Output Redirection in Linux.
Input File
In the directory where your program is located, create a text file (for example, input.txt) and put the input data you want to provide to your program in that file. For example, if your program expects a line of text and then a series of numbers as input, your input.txt file might look like this:
My Program
17
23
That would be equivalent to typing "My Program" followed by Enter, then "17" followed by Enter, then "23" followed by Enter when the program is running.
Manual Input Redirection
When running your program from the command line, you can use the < operator to redirect input from a file. For example, if your program is called program.exe, you would run it like this:
./program.exe < input.txt
This command tells the shell to take the contents of input.txt and provide it as standard input to program.exe.
Input Redirection with the Debugger
When using the VS Code debugger, you are not executing the program yourself. Instead, the debugger is executing it for you. Thus, we need to tell the debugger to use input redirection.
To do so, open your launch.json file (in the .vscode folder of your project). It has a list of configurations. Each configuration is a JSON object (enclosed in {} braces). They will have names like Run Program, Run Program (Mac), Run Tests, and Run Tests (Mac).
In each configuration where you want to use input redirection, add the following line:
"args": ["<","${workspaceFolder}/input.txt"],
A good place for this new line is just below the line that says:
"cwd": "${workspaceFolder}",
(It is safe to add the line to configurations you are not currently using, so if in doubt, just add it to all of them.)