Mukkho Shukkho Manush Mukkho Shukkho Manush - 1 month ago 6
C++ Question

Command to compile C++ which inputs from file

myC.cpp

#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
freopen("input.txt","r",stdin); // All inputs from 'input.txt' file

int n,m;
cin>>n>>m;
cout<<(n+m)<<endl;
return 0;
}


The file
input.txt
may contains:

Input.txt


10 20


For the command


g++ myC.cpp -o myC

myC


It'll produce output
30
getting input from
input.txt


Now I am looking for a command which will automatically get input from a file without using freopen() inside the code like-


g++ myC.cpp -o myC -i input.txt

Answer

You need to pipe the input file to your program when invoking it from the command line. Consider the following program:

#include <stdio.h>

int main( void ) {

  int a, b;

  scanf( "%d", &a );
  scanf( "%d", &b );

  printf( "%d + %d = %d", a, b, ( a + b ) );

  return 0;
}

... say I compiled it as "test.exe", I would invoke it as follows to pipe the input text file.

./test.exe < input.txt