How to automatically provide sample input to program from a file ?

Can anyone explain how to easily provide the sample input cases to the written code in IDE from a file or any other simple method so writing the testcases over and over again while testing can be avoided ?

This will be surely helpful to most of us,

Let’s say you want to read the input from a file input.txt. Create input.txt in the same place as your program. After that just in the beginning of your int main() function write this freopen("input.txt","r",stdin);. Doing this would read input from the filw and you won’t have to provide the input again and again. You can also write the output to a file. Same way create output.txt and write freopen("output.txt","w",stdout);. This would write the output in the specified file .

One more thing,remember to comment out the lines before submitting your code or it might cost a Runtime Error.

Ask if you run into any trouble with this.

Hope this helps.

4 Likes

This will be very helpful to you.

If you’re using the command line to run your program(i use linux). You should create a file named input(or anything! Just remember the name). Write the input test case in it(i usually copy paste the input from the contest page). Now compile your program. An executable file will be created as always. Lets assume its name be “p”(created by using gcc -o p prog-name.c). Now, just use this instead of(./p)
: “./p <input” in place of input you can also use a txt file. Just write its name in the place of input. Use all statements without double-quotes.

Please upvote this answer if it is helpful to you.

3 Likes

Hello shubham99, i totally agree with sarvagya3943, but there is a trick with which you can submit the same code on online sites and which works well on your local computer as well.

Just type freopen(“inp.txt”, “r”, stdin); and freopen(“out.txt”, “w”, stdout); inside the #ifndef and #endif tags.

You can see a sample ac solution of mine at CodeChef: Practical coding for everyone

2 Likes

Can you provide a sample program for this maybe ? I tried this on TEST problem but I don’t think I got it.Here’s the link to code - http://ideone.com/m7OW75

Please correct it. Thanks :slight_smile:

Thanks :).

I think you didn’t understand. freopen() won’t work on online platforms, try it on your local IDE. This helps for example,during a contest when you want to test your code repeatedly, so instead of providing input again and again you just take the input from the file. Saves a lot of time. Do this when on your local computer and submit this on the site(comment out the lines). Hope I made some sense.

Forgot to mention that!

1 Like

really helpful, thanks.

If you use Vscode, you can use GitHub - mfornet/acmx: Competitive programming made simple. VSCode extension.