gpt4 book ai didi

c - 如何通过使用和创建函数来计算命令行参数中的字符数

转载 作者:太空宇宙 更新时间:2023-11-04 06:27:11 25 4
gpt4 key购买 nike

我无法理解如何创建一个函数来计算命令行参数中的字符数。它只需在“my_strlen()”函数中计算结果,然后在 main() 中打印结果。我是 C 的新手,但这是我到目前为止的代码;

int my_strlen(  char string[]);
{
strcpy(string, argv[1];
return 1;
}
int main(int argc, char *argv[])
{
if(argv != 2)
{
printf("You must run this program with an argument\n");
return 2;
}
printf("%d", strlen(string);
return 0;
}

如您所见,我很困惑,我也不知道如何存储 strlen(string) 的值以便稍后将其作为自己的整数调用。

最佳答案

试试这个简单的代码。

#include <stdio.h>
#include <string.h>

/* Function to calculate length of given string */
int my_strlen(char *input_string)
{
/* Loop through all the characters in the string till null-terminator */
int i;
for(i=0; input_string[i] != '\0'; i++);
return i;
}

int main(int argc, char *argv[])
{
int length = -1;
if(argc != 2) /* Check the number of command line arguments */
{
printf("You must run this program with an argument\n");
return 2;
}
else
{
/* Your function to calculate length of the string */
length = my_strlen(argv[1]);
printf("Length of command line argument is: %d\n", length);
}
return 0;
}

这里
argv[0] 是程序名。
argv[1] 是程序的参数。

关于c - 如何通过使用和创建函数来计算命令行参数中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25578886/

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