【问题标题】:Running C++ with input in the command line在命令行中使用输入运行 C++
【发布时间】:2020-08-11 06:25:56
【问题描述】:

我需要通过在 linux shell 中键入以下代码来让我的程序运行

./[program name] < [input file name]
e.g. ./program1 < input.txt

程序包括,例如

int main(int argc, char ** argv){
    string file;
    cin >> file;
    fstream input_file (file, fstream::in);
}

当我输入时它会起作用

./program1
input.txt 

但不是什么时候

./program1 < input.txt

有什么帮助吗?

【问题讨论】:

  • input.txt的内容是什么
  • ./program1 &lt; input.txt 正在使用input.txt 的内容来获取要打开的文件名。
  • @KORguy 您的 input.txt 包含您要打开的文件的名称??
  • 该文件中的第一个数字是您要打开的文件的名称吗?这就是您的代码正在尝试的。您可能希望更改程序以使用命令行参数,而不是提示输入文件名或仅在未传递参数时提示。 https://www.geeksforgeeks.org/command-line-arguments-in-c-cpp/
  • 这不是命令行参数。摆脱&lt;,因此在修改您的程序以处理命令行参数后,使用./program1 input.txt 或者修改程序以仅从cin 读取数据,这意味着不要询问文件名。 ./program1 &lt; input.txt 将支持从 cin 读取

标签: c++ shell command


【解决方案1】:

如果您只想要数据,则无需使用fstream 打开文件。

使用./program &lt; input.txt调用代码。

代码:

int main() {
    // no need to open file here start reading data directly from input.txt
    int n;
    std::cin >> n;
    std::cout << n; // should print the first number present in your input.txt file.
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    • 2017-01-19
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多