0

我想在 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

4 回答 4

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;
   }
}
于 2012-06-11T07:45:21.080 回答
2

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

// 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";
}
于 2012-06-11T14:25:18.617 回答
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。

于 2012-06-11T07:43:03.583 回答
-2

使用重定向:

./yourprogram < input1

在 Linux 控制台和 MSDos 下都可以工作。

于 2012-06-11T07:41:37.353 回答