【问题标题】:How to copy and run command in different terminal如何在不同的终端复制和运行命令
【发布时间】:2016-08-06 05:54:20
【问题描述】:

我有一个简单的程序,例如在 C++ 中

#include<iostream>
using namespace std;

int main()
{
    int a, b, c;
    cin >> a >> b;
    c = a + b;
    cout << c;
}

这里我需要在执行时提供ab 作为输入。

我需要编写一个脚本来将 a(比如 5)和 b(比如 7)的值自动输入到第一个终端。

【问题讨论】:

  • 阅读管道和echo 命令
  • 您是否考虑过编写脚本来启动程序本身,然后直接与其交互而不是尝试使用多个终端?
  • 另一个更简单的建议是让您的 C++ 程序接受命令行参数,以便您的脚本可以使用任何所需的输入调用它(例如 ./your-program.out 5 7)。您的 C++ 程序只需要将输入的数字字符串转换为实际数字(参见 atoi 函数)
  • 请不要忘记回来投票+接受您认为最有帮助的答案。它可以帮助社区中的每个人。

标签: c++ terminal xterm gnome-terminal


【解决方案1】:

我认为您必须更改某些内容才能这样做,因为您想从脚本中传递参数。 C++程序main.cpp:

 #include <iostream>
#include <stdlib.h>
using namespace std;
int main(int argc,char *argv[])
{
  if(argc==1)
   {
    exit(1);
   }
  int a=atoi(argv[1]);
   int b=atoi(argv[2]);
  cout<<a+b<<endl;
return 0;
}

shell 脚本将是:

 #!/bin/bash

    g++ temp.cpp -o out
    a=5
    b=2
    ./out "${a}" "${b}"

你应该看到 here 来传递变量。并且看到 this also

【讨论】:

  • 我想我应该刷新一下页面...我在发布我的帖子后注意到了您的回复,我们最终按照相同的思路思考:\
  • @ray 我想不出两个代码是一样的。但是,如果您看到已回答的时间,它就会解决。
  • 不,只是我们提出了类似的解决方案。我们的代码肯定不一样,在我之前我没有看过你的帖子。但是我们仍然为相同的问题提供了类似的解决方案。我们都应该对此感觉良好。
  • 如果我想传递一个数组怎么办?? a[0]=5 ,a[1]=2 ,?这行得通吗?
【解决方案2】:

与其尝试编写一个与多个终端交互或与管道一起工作的程序,这可能更复杂,我建议让您的程序更简单,让它处理命令行参数。您可以按如下方式重写您的 C++ 程序:

#include <iostream>
#include <cstdlib>    // for atoi function

using namespace std;

int main(int argc, char* argv[])  // to accept CLI inputs
{
    // argv[0] has path/name to this program
    // argv[1] has 1st argument, if provided
    // argv[2] has 2nd argument, if provided
    // if argc != 3, then we don't have everything we expected, and we bail
    if(argc != 3) {
        cerr << "usage: " << argv[0] << " arg1 arg2" << endl;
        return -1;
    }

    // for simplicity, we assume that you won't get letters, only numbers
    int a = atoi(argv[1]);
    int b = atoi(argv[2]);
    cout << (a + b);

    return 0;
}

然后您可以编写一个简单的 shell 脚本来使用您想要的任何参数来启动您的程序。例如,如果你构建的程序被称为test(使用g++ -o test test.cpp来构建),那么你可以使用这个例子launcher.bash脚本:

#!/bin/bash

for i in {0..10}
do
    ./test $i $i
    echo
done

脚本产生以下输出:

/tmp ❯ ./launcher.bash
0
2
4
6
8
10
12
14
16
18
20

【讨论】:

    【解决方案3】:

    如果可执行文件是 a.out 那么你可以使用

    a=5;b=7;echo $a $b | ./a.out

    顺便说一句,在您的示例中,缺少 cout/cinnamespace(例如,在 # 之后添加 using namespace std;包括)。

    【讨论】:

      猜你喜欢
      • 2019-03-27
      • 1970-01-01
      • 2017-08-28
      • 2015-04-02
      • 2022-01-12
      • 2020-09-03
      • 2019-12-22
      • 2021-02-17
      • 1970-01-01
      相关资源
      最近更新 更多