猿问

从命令行将参数传递到C程序

因此,我在Linux中,并且希望有一个程序在从命令行执行时接受参数。


例如,


./myprogram 42 -b -s


因此,程序会将数字42存储为int类型,并根据代码得到的-b或-s参数执行代码的某些部分。


海绵宝宝撒
浏览 784回答 3
3回答

三国纷争

您可以使用getopt。&nbsp;#include <ctype.h>&nbsp;#include <stdio.h>&nbsp;#include <stdlib.h>&nbsp;#include <unistd.h>&nbsp;int&nbsp;main (int argc, char **argv)&nbsp;{&nbsp; &nbsp;int bflag = 0;&nbsp; &nbsp;int sflag = 0;&nbsp; &nbsp;int index;&nbsp; &nbsp;int c;&nbsp; &nbsp;opterr = 0;&nbsp; &nbsp;while ((c = getopt (argc, argv, "bs")) != -1)&nbsp; &nbsp; &nbsp;switch (c)&nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp;case 'b':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;bflag = 1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break;&nbsp; &nbsp; &nbsp; &nbsp;case 's':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sflag = 1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break;&nbsp; &nbsp; &nbsp; &nbsp;case '?':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (isprint (optopt))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fprintf (stderr, "Unknown option `-%c'.\n", optopt);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fprintf (stderr,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Unknown option character `\\x%x'.\n",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; optopt);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return 1;&nbsp; &nbsp; &nbsp; &nbsp;default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;abort ();&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;printf ("bflag = %d, sflag = %d\n", bflag, sflag);&nbsp; &nbsp;for (index = optind; index < argc; index++)&nbsp; &nbsp; &nbsp;printf ("Non-option argument %s\n", argv[index]);&nbsp; &nbsp;return 0;&nbsp;}

小唯快跑啊

在C语言中,这是通过传递给main()函数的参数来完成的:int main(int argc, char *argv[]){&nbsp; &nbsp; int i = 0;&nbsp; &nbsp; for (i = 0; i < argc; i++) {&nbsp; &nbsp; &nbsp; &nbsp; printf("argv[%d] = %s\n", i, argv[i]);&nbsp; &nbsp; }&nbsp; &nbsp; return 0;}可以在网上找到更多信息,例如主要文章的论点。
随时随地看视频慕课网APP
我要回答