使用来自文件的输入运行 C++ 的命令

Par*_*Deb 2 c++ command

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;
}
Run Code Online (Sandbox Code Playgroud)

该文件input.txt可能包含:

输入.txt

10 20

用于构建和运行代码的命令行 -

g++ myC.cpp -o myC
myC
Run Code Online (Sandbox Code Playgroud)

它产生30input.txt文件中获取输入的输出。

现在我正在寻找一个命令,它同样可以从文件中获取输入,但希望避免在代码中使用 freopen()。

可能是这样的——

g++ myC.cpp -o myC  // To compile
myC -i input.txt    // To run with input
Run Code Online (Sandbox Code Playgroud)

Jac*_*ack 6

从命令行调用输入文件时,您需要将输入文件通过管道传输到您的程序。考虑以下程序:

#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;
}
Run Code Online (Sandbox Code Playgroud)

...说我将它编译为“test.exe”,我会按如下方式调用它来管道输入文本文件。

./test.exe < input.txt
Run Code Online (Sandbox Code Playgroud)