如果用户为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);
}
当我以argv [1]的形式输入--help时,预期的输出应该是help_info函数中的信息。我得到的输出每次都是“程序名称--help Hi”。任何建议表示赞赏!
答案 0 :(得分:2)
不要实现自己的strcmp
;这是不确定的行为,很可能比标准C库实现的行为要慢。
话说回来,while
中strcmp
循环的控制条件是错误的。它不会在字符串末尾的终止空字符处停止。
要解决此问题,请执行以下操作:
while (*cmp1 && *cmp1 == *cmp2)
代替此:
while (*cmp1 == *cmp2)
要解决未定义的行为,可以命名函数compare_string
或类似的名称(只要名称不以str
开头),然后更改{{1}的用法}。