【发布时间】:2014-04-30 23:55:29
【问题描述】:
我正在尝试学习如何接受命令行参数和伴随标志的数据,即
myprogram -sampleflag datahere
到目前为止,我的代码就在这里。 getopt() 将数据放入变量c,显然您可以从调用它的函数外部访问optarg。这怎么可能?根据手册页,我的代码应该可以工作!但是,如您所见,输出为 (null)。
我的代码:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
opterr = 0;
char* cvalue = NULL;
int c;
char* optarg = hello;
while((c = getopt(argc, argv, "ps")) != -1){
switch(c){
case 'p':
cvalue = optarg;
printf("cvalue is : %s\n", cvalue );
break;
}
}
}
我的输出:($ myprogram -p test)
cvalue is : (null)
【问题讨论】:
-
+1 恭喜您提出了格式正确的问题。
-
谢谢!第一个也是!
-
欢迎来到 SO。如果这是第一个待解决的问题,我鼓励您使用“真实”用户名。我倾向于忽略用户 NNNNNNN 的问题,因为这些问题的质量普遍较低,并且会被问到“为我做我的工作”。
-
@StephenP 我有相反的经历;就我个人而言,我从不根据句柄对问题进行评分。
-
@self — 我不根据句柄 评分,但我不太可能将时间花在“路过”问题上 — 有很多来自匿名用户的坏消息,他们在询问之前懒得搜索,我厌倦了浪费我仅有的一点“空闲”时间。