Taking inputs from input files and Test cases

How can we take inputs from the input files and make our output in output files. What exactly does test cases mean?

I believe you are asking this for local testing purpose.

One way is to use freopen to associate a file to stdin or stdout.

    freopen("in.txt", "r", stdin);

The ifndef guard is necessary so that freopen is not compiled on judge. You can add your test cases in “in.txt”, and don’t need to type out input for each run.

If you use terminal you can do stream redirection like-

./a.out < in.txt > out.txt

you can also use :

//Header Files

using namespace std;

//Variable declaration
string s,t;

int main()


ifstream in; //Creating object for input stream
ofstream out; //Creating object for output stream

in.open("file.txt");    //open a file to read input
out.open("output.txt"); //open a file to write output

while(in>>s)            // fetch each word
  . //your code
   out<<s<<" ";         //writing to a file
in.close();             //closing the input file
out.close();            //closing the output file

return 0;


Actually in fb hacker cup,…as they give that download the input file ( input file have the test cases ) and then output a output file…so…how do we put test cases as inputs in c programming…

I believe I have answered just that. You can read from stdin (like through scanf or std::cin) and output to stdout (like through printf or std::cout). And then use either freopen or stream redirection to read/write from/to file.

BTW the ONLINE_JUDGE guard works for codechef only. So if you want to use freopen, comment it out before submitting the code online.

Thanks sir…but how can we take the input from a text file ?? do we need to type the inputs one by one ? how can we do this in case of php programming ? how can we run php programs from command line by giving inputs ? Thanks…

What I have mentioned is the way of taking input from text file!!

Just type out your desired test case in a plain text file (like in.txt), then use either of the 2 ways to read from text file instead of stdin. Please try it out, it is quite simple.

I haven’t done it with PHP, so can’t comment about that.