本文主要介绍如何使用C++语言编写一个接收用户输入参数的小程序。接收用户输入参数的程序,在 linux 系统中很常见,如一些常见的命令,都会需要接收用户输入的参数,并根据这些参数进行不同的操作。
1 示例程序
在这里展示一个的示例程序,该程序接收输入的三个参数,并将这三个参数打印出来。代码(rec_user_arg.cpp)如下:
#include <iostream>
#include <string.h>
using namespace std;
void ShowUsage()
{
cout << "Usage : rec_user_arg <--name=your name> [Option]" << endl;
cout << "Options :" << endl;
cout << " --name=your name Your name, this option MUST be given." << endl;
cout << " --occupation=your occupation Your occupation, such as paladin." << endl;
cout << " --camp=your camp Your camp, such as alliance." << endl;
cout << " --help Print this help." << endl;
return;
}
int main(int argc, char *argv[])
{
// 如果用户没有输入参数,则提示错误信息并退出
if (argc < 2)
{
cout << "No arguments, you MUST give an argument at least!" << endl;
ShowUsage();
return -1;
}
int nOptionIndex = 1;
string strName;
string strOccupation;
string strCamp;
while (nOptionIndex < argc)
{
// 获取用户姓名
if (strncmp(argv[nOptionIndex], "--name=", 7) == 0)
{
strName = &argv[nOptionIndex][7];
}
// 获取用户职业
else if (strncmp(argv[nOptionIndex], "--occupation=", 13) == 0)
{
strOccupation = &argv[nOptionIndex][13];
}
// 获取用户阵营
else if (strncmp(argv[nOptionIndex], "--camp=", 7) == 0)
{
strCamp = &argv[nOptionIndex][7];
}
// 显示帮助信息
else if (strncmp(argv[nOptionIndex], "--help", 6) == 0)
{
ShowUsage();
return 0;
}
else
{
cout << "Options '" << argv[nOptionIndex] << "' not valid. Run '" << argv[0] << "' for details." << endl;
return -1;
}
nOptionIndex++;
}
cout << "Name is: " << strName << endl;
cout << "Occupation is: " << strOccupation << endl;
cout << "Camp is: " << strCamp << endl;
return 0;
}
编译并执行上述代码,结果如下:
1. 用户没有输入参数时:
2. 用户输入了两个参数时:
3. 用户输入了错误的选项时: