gpt4 book ai didi

c - 当我的 --help 信息是我的 argv[1] 时,有什么原因不会打印?任何建议表示赞赏

转载 作者:行者123 更新时间:2023-11-30 18:44:29 26 4
gpt4 key购买 nike

如果用户为 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”。如有任何建议,我们将不胜感激!

最佳答案

不要实现您自己的strcmp;它是未定义的行为,并且很可能比标准 C 库实现的行为慢。

话虽如此,strcmpwhile 循环的控制条件是错误的。它不会在字符串末尾的终止空字符处停止。

要解决这个问题,请执行以下操作:

while (*cmp1 && *cmp1 == *cmp2)

而不是这个:

while (*cmp1 == *cmp2)

为了解决未定义的行为,您可以将函数命名为 compare_string 或类似的名称(只要名称不以 str 开头),然后更改使用 strcmp 来实现这一点。

关于c - 当我的 --help 信息是我的 argv[1] 时,有什么原因不会打印?任何建议表示赞赏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57845419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com