gpt4 book ai didi

c - 如何检查 argv[1] 是否以特定字符结尾?

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

我试图弄清楚如何将 argv[1] 值与几个测试用例进行比较。我想看看 argv[1] 是否以特定的 char 值结尾。到目前为止,我有以下代码:

int main(int argc, char * argv[])
{
char strin[250];
int length;
printf("The argument supplied is %s\n", argv[1]);
strcpy(strin,argv[1]);
length = strlen(strin);
printf("Testing: %c",strin[length]);
if( strin[length] = 'b')
{
printf("b in the input");
}

}

但出于某种原因,每当我输入任何输入时,打印语句都会触发。我如何检查命令行参数中的最后一个字符是否等于我将其设置为等于的字符?

最佳答案

基本上,您只需执行以下操作:

int main(int argc, char * argv[]) {
// check if there's an argument to test
if (1 > argc) {
// extract the position of the last character
int last_pos = strlen(argv[1])-1;
// compare the last character with the character "b"
if (0 <= last_pos && 'b' == argv[1][last_pos]) {
printf("Hoora! The input ends with b!");
return 0;
} else {
printf("Bummer… The input does not end with b :(");
}
} else {
printf("there's no argument to test!");
}
}

现在,这里是错误的总结:

int main(int argc, char * argv[])
{
char strin[250];
int length;
printf("The argument supplied is %s\n", argv[1]);

// you're doing a copy from the first argument into the
// variable strin. If argv[1] is 251 characters, you'll
// overwrite memory, and will cause a "buffer overflow".
// Whenever you need to do strcpy of data input by a user
// use strncpy().
strcpy(strin,argv[1]);

// you're extracting the /length/ of the string, not the /position/
// of the last character, so when you're trying to access at index
// length, you'll get data from one character beyond the array.
length = strlen(strin);

// so here you're seeing a random value from the memory of your computer
printf("Testing: %c",strin[length]);

// here you made a mistake and you're assigning the value 'b' to the
// value beyond the allocated memory for the array. Basically:
// Here be dragons.

// To avoid that mistake, always put the value you're comparing against
// in a comparaison on the Left Hand Side, and the value you're comparing
// on the right hand side. Then the compiler will yell at you!
if( strin[length] = 'b')
{
printf("b in the input");
}

}

关于c - 如何检查 argv[1] 是否以特定字符结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39794354/

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