在C ++程序的运行时输入输入值(./filename.out)

时间:2012-06-11 07:29:24

标签: c++ g++

我想在C ++程序的运行期间输入用户输入,即./a.out期间 插图:./ a.out input1 input2

C ++程序是:

添加两个数字的程序

#include<iostream>
using namespace std; 
int main()
{
    int a, b;
    cin >> a >> b;
    int c = a + b;
    cout << "The sum of two numbers is : " << c << "\n";
}

现在请帮我在运行时输入a和b的值,同时在linux终端运行输出文件。

4 个答案:

答案 0 :(得分:2)

试试这个(不要忘记包含适当的标题)

int main(int argc, char** argv)
{
   if ( argc == 3 ) // command line has three arguments, the program, arg1 and arg2
   {
     int sum = atoi(argv[1]) + atoi(argv[2]);
     cout<<"The sum of two numbers is : "<< sum << endl;
   }
   else
   {
     cout << "wrong number of arguments, expected two numbers" << endl;
     cout << "yourprogramname {number1} {number2}" << endl;
   }
}

答案 1 :(得分:2)

对于许多简单用途,Boost Program.Options提供了许多用于处理命令行参数的样板代码。来自tutorial

// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
    ("help", "produce help message")
    ("compression", po::value<int>(), "set compression level")
;

po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);    

if (vm.count("help")) {
    cout << desc << "\n";
    return 1;
}

if (vm.count("compression")) {
    cout << "Compression level was set to " 
 << vm["compression"].as<int>() << ".\n";
} else {
    cout << "Compression level was not set.\n";
}

答案 2 :(得分:0)

#include <iostream>
#include <cstdlib>

int main(int argc, char *argv[]) {
    using namespace std;
    int a = atoi(argv[1]);
    int b = atoi(argv[2]);
    cout << a+b << endl;
    return 0;
}

将获取命令行参数并打印它们。 atoi将字符串转换为int。

答案 3 :(得分:-2)

使用重定向:

./yourprogram < input1

在Linux控制台和MSDos下都可以使用。