【发布时间】:2019-09-10 09:40:17
【问题描述】:
如果用户为 argv[1] 输入 --help 语句,我将无法打印它。对于我可能做错的事情,任何人都可以提供任何建议吗?感谢您提供的任何帮助。
我有 strcmp 函数来逐个字符比较两个字符串,看看第一个参数是 --help 还是其他。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void help_info(char * info);
void numarg_error_message(char * info2);
int strcmp(const char *string, const char *string2);
int main(int argc, char* argv[])
{
char *helping;
char *helping1;
int i, c;
int num_sum = 0;
for (i = 0; i < argc ; i++)
{
printf("%s ", argv[i]);
//c = atoi(argv[i]);
//num_sum += c;
}
if (argc < 2)
{
numarg_error_message(helping1);
}
else if (strcmp(argv[1], "--help") == 0)
{
help_info(helping);
}
else
{
printf("Hi");
}
return 0;
}
void help_info(char* help)
{
printf("Usage: p2\n\n");
printf("p2 --help\n");
printf("\tdisplay thus usage material.\n\n");
printf("p2 <1> [<0> <1> ...]\n");
printf("\t calculate the sum, minimum, maximum and mean of the real\n");
printf("\t number arguments. Non-numeric values will be echoed to\n");
printf("\t stdout, one per line, with the numeric results printed\n");
printf("\t following the non-numeric lines.\n\n");
}
void numarg_error_message(char *errormessage)
{
char *help3;
printf("Error: not enough arguments.\n");
help_info(help3);
}
int strcmp(const char * str1, const char * str2) //comparing two strings
{
const char *cmp1 = str1;
const char *cmp2 = str2;
while (*cmp1 == *cmp2)
{
cmp1++;
cmp2++;
}
return (*cmp1 - *cmp2);
}
当我输入 --help 作为我的 argv[1] 时,预期的输出应该是 help_info 函数中的信息。我得到的输出每次都是“程序名称--help Hi”。任何建议表示赞赏!
【问题讨论】:
-
@user3121023 此外,除非代码被编译为独立的,否则具有与标准库函数同名的函数是未定义的行为。
标签: c command-line-arguments strcmp