C++开关语句,使用命令行参数

C++ switch statements, using command line arguments

本文关键字:命令行 参数 开关 语句 C++      更新时间:2023-10-16

我正在尝试使用switch语句来启动函数调用。需要在来自命令行参数的参数中传递到switch语句中的值,这意味着它存储在argv[]中。在我的例子中,已知这个参数存储在argv[5]中。我的问题是,我不知道如何正确转换或存储argv[5]中的值,以便switch语句可以读取它。我尝试使用char*、char[]和string作为变量"verbose"的数据类型

我一直得到的错误是:语句需要整数类型的表达式('char*'无效)开关(冗长)^~~~~~~

我的代码如下:

char* verbosity = argv[5];
cout << endl << verbosity;
switch(verbosity)
{
case 'vlow':
{
   vlow();//calls vlow function
   break;
}
case 'vmed':
{
   vmed();//calls vmed function
   break;
}
case 'vhigh':
{
   vhigh();//calls vhigh function
   break;
}
default:
   break;
}

我应该使用某种格式将argv[]中的字符串传递到switch语句中吗?

'vlow'是一个多字符文字,而不是字符串文字。

要比较C样式字符串,请使用std::strcmp,如下所示:

if (std::strcmp(verbosity, "vlow") == 0)
{
   //process
}

请注意"vlow"与双引号的使用。