将变量从bash传递到可执行文件(使用stdin读取参数)

时间:2015-04-29 15:11:02

标签: bash variables executable stdin

我有以下 test.cpp c ++程序

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int main()
{
    float a,b,c;
    cout<<"Give 1st number";
    cin>>a;
    cout<<"Give 2nd number:";
    cin>>b;

    c=a+b;
    cout<<"\n"<<a<<"+"<<b<<"="<<c<<endl;

return 0;
}

我想创建一个 shell脚本,它提供输入变量。 我知道如何传递一个变量,我想知道是否有办法传递2个变量 ... 比如以下 test.sh 文件无法正常工作

#!/bin/bash

g++ test.cpp -o testexe
chmod +x testexe

a=1
b=2

./testexe <<< $a $b

2 个答案:

答案 0 :(得分:3)

要兼容bash,还要兼容face_detect::face_detect(QWidget *parent) : QWidget(parent) { imgwidget = new showwidget("D:\\sample.avi"); imgwidget->resize(QSize(640,480)); setWindowTitle(tr("Face Detection!")); FaceNumLabel = new QLabel(tr("face_num: ")); num = new QLabel; num->setFrameStyle(QFrame::Panel | QFrame::Sunken); ImgSource = new QLabel(tr("image source: ")); VedioBtn = new QPushButton(tr("from vedio")); LocalImgBtn = new QPushButton(tr("local image")); LeftLayout = new QVBoxLayout(); LeftLayout->addWidget(imgwidget); LeftLayout->addWidget(FaceNumLabel); LeftLayout->addWidget(num); //LeftLayout->addWidget(ShowImageLabel, 3, 0, 1, 2); RightLayout = new QVBoxLayout(); RightLayout->addWidget(ImgSource); RightLayout->addWidget(VedioBtn); RightLayout->addWidget(LocalImgBtn); RightLayout->addWidget(ImgSource); QHBoxLayout *mainLayout = new QHBoxLayout(this); mainLayout->addLayout(LeftLayout); mainLayout->addLayout(RightLayout); mainLayout->setSizeConstraint(QLayout::SetFixedSize); connect(VedioBtn, SIGNAL(clicked()), this, SLOT(openvedio())); connect(LocalImgBtn, SIGNAL(clicked()), this, SLOT(localimg())); } - 同时避免管道开销 - 使用heredoc:

/bin/sh

如果您不关心管道开销(并且仍然保持./testexe <<EOF $a $b EOF 兼容性,那么使用/bin/sh的任何答案都缺乏):

<<<

如果您不关心printf '%s\n' "$a" "$b" | ./testexe 兼容性:

/bin/sh

答案 1 :(得分:1)

您应该按如下方式更改C ++程序和脚本:

int main(int argc, const char*argv[])
{
    float a,b,c;
    a=std::stof(argv[1]);
    b=std::stof(argv[2]);
    c=a+b;
    cout<<"\n"<<a<<"+"<<b<<"="<<c<<endl;
    return 0;
}


#!/bin/bash

g++ test.cpp -o testexe
chmod +x testexe

a=1
b=2

./testexe  $a $b