命令行参数为 –s ok 显示 HelloWorld,否则显示 Error 用getopt 函数实现
zxxvggfccccc
//"myapp.cc"
#include
#include
int main(int argc, char** argv)
{
opterr = 0;
if ( getopt(argc,argv,"-s") == 's')
printf("HelloWorld\n");
else
printf("Error\n");
return 0;
}
$ gcc -o myapp myapp.cc
$ ./myapp -s
HelloWorld
$ ./myapp -h
Error
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int opt;
char *optstr = "s:";
while ((opt = getopt(argc, argv, optstr)) != -1) {
switch (opt) {
case 's':
if (strcmp(optarg, "ok") == 0) {
printf("HelloWorld\n");
}
break;
default:
printf("Error\n");
}
}
return 0;
}
// 使用C标准库中的getopt函数,可以获取命令行参数。当命令行参数为"-s ok"时,程序会输出"HelloWorld";否则,输出"Error"。具体实现方法是使用getopt函数获取命令行参数,然后对比参数是否为"-s ok",最后输出对应的结果。