如果有一个程序,main的形参列表中有一些参数,例如int或一个其他的类型,而我需要从其他程序中调用这个程序,并传一定参数,应该怎么办啊?
有试过ShellExecute,但是不知道应该如何传一个任意类型的参数(好多都是用string来举例,而ShellExecute第四个函数只能传入字符串啊)
C++默认main只有两种形式吧int main()
和int main(int argc,char*argv[])
所以说,应该只能传入字符串吧
你可以参考下面例子
main.cpp
#include <iostream>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
int main(int argc, char *argv[])
{
int int_value;
std::string string_value;
po::options_description desc("Options");
desc.add_options()
("help,h", "print help message")
("int,i", po::value<int>(&int_value)->default_value(0), "int value")
("str,s", po::value<std::string>(&string_value), "string value");
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, desc), vm);
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
std::cerr << desc << '\n';
return 1;
}
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
return 0;
}
std::cout << "int value: " << int_value << '\n';
std::cout << "string value: " << string_value << '\n';
return 0;
}
main2.cpp
#include <cstdlib>
int main()
{
std::system("./main -i 123 -s abc");
return 0;
}
$ g++ -Wall main.cpp -o main -lboost_program_options
$ g++ -Wall main2.cpp -o main2
$ ./main -h
Options:
-h [ --help ] print help message
-i [ --int ] arg (=0) int value
-s [ --str ] arg string value
$ ./main -s aaa -i 111
int value: 111
string value: aaa
$ ./main2
int value: 123
string value: abc