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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17531573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:16:08  来源:igfitidea点击:

Command to run C++ with input from file

c++command

提问by Partharaj Deb

myC.cpp

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.txtmay contains:

该文件input.txt可能包含:

Input.txt

输入.txt

10 20

10 20

Command lines to build and run the code-

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

g++ myC.cpp -o myC
myC

It produces output 30getting input from input.txtfile.

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

Now I am looking for a command which will similarly get input from a file, but want to avoid using freopen() inside the code.

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

It might be something like this-

可能是这样的——

g++ myC.cpp -o myC  // To compile
myC -i input.txt    // To run with input

回答by Jacob Pollack

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”,我会按如下方式调用它来管道输入文本文件。

./test.exe < input.txt

回答by David Rodríguez - dribeas

While there is no single command that will do that (the compiler will not execute your code), for small tests I tend to run a single command line that will compile and execute if the build was correct:

虽然没有单个命令可以做到这一点(编译器不会执行您的代码),但对于小型测试,我倾向于运行一个命令行,如果构建正确,它将编译和执行:

g++ -o myC myC.cpp && ./myC input.txt

g++ -o myC myC.cpp && ./myC input.txt

Of course that requires changing your program so that the filename is taken as an argument, but that should be simple enough.

当然,这需要更改您的程序,以便将文件名作为参数,但这应该足够简单。