skip to Main Content

Generally we need to type the input after running any file where we have std::cin, like the C++ code in below

#include <iostream>
using namespace std;
int main()
{
    // your code goes here
    int t;
    cin >> t;
}

I just don’t like to enter the same input every time. So I want to automate this process for the same input, say I save my input in a file called input.txt and after running the file, it should take the input from input.txt and output the results. Of course saving input to the clipboard is one way but I might want to copy other things while coding and copy-pasting is itself is again one small job.

I use VS code editor in windows and run code in terminal extension.

2

Answers


  1. The solution is to learn to use your shell. I’m assuming a Unix-like shell here.

    Type all of your inputs into a file as you would enter them while the program is running. Save it.

    When you run your program, use the command a.out < input.txt. Substitute the appropriate names, obviously.

    Your program will read the inputs from the file as if they had been typed in.

    Note that because nothing was actually typed in, your formatting might look a bit off, but it’s not a big deal compared to the time you’re saving in running your tests.

    Login or Signup to reply.
  2. You could use, following function inside your main function

    int main() {
    freopen('input.txt', 'r', stdin);
    freopen('output.txt', 'w', stdout); //if you want to save output to a file.
    /*
    ... your code 
    */
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search