我目前正在开发一个 C 程序,它可以接受命令行参数并以各种方式操作它们。在这个特定的片段中,我想通读每个传递的参数,并检查单词“Candy”是否以任何可能的方式出现。到目前为止,这就是我所拥有的......
// To test if "Candy" appears in the argument
if (strcmp(argv[i], "Candy", 5) == 0)
{
printf("Candy!\n", argv[i+1]);
}
我的问题是我是否正确使用了 strcmp
语句?我在这里寻找过这个问题,但我似乎找不到任何 C 语言的具体例子。任何帮助深表感谢!
最佳答案
您绝对走在正确的道路上!
但是请注意:函数strcmp的原型(prototype)是
int strcmp(const char *str1, const char *str2)
--> 它只需要两个参数,而不是三个!
如果你想测试一个参数是否是“Candy”,正确的方法是:
// To test if "Candy" appears in the argument
if (strcmp(argv[i], "Candy") == 0)
{
printf("Candy!\n");
// printf("Candy!\n", argv[i+1]); <- why the argv[i+1] in the original question?? too many arguments for printf...
}
顺便问一下,你用的是什么编译器?从表面上看,您应该收到各种错误和警告!
<小时/>或者,如果您想查找参数是否包含单词 Candy(如 SugarCandy 或 SmellyCandyIsBad),您应该使用 strstr() 而不是 strcmp()。引用,
Description
The C library function char
*strstr(const char *haystack, const char *needle)
function finds the first occurrence of the substring needle in the string haystack. The terminating '\0' characters are not compared.Declaration
Following is the declaration for strstr() function.
char *strstr(const char *haystack, const char *needle)
这意味着要测试字母“Candy”是否出现在参数字符串中,必须执行以下操作:
// To test if "Candy" appears in the argument in any form
if (strstr(argv[i], "Candy")) // strstr != 0
{
printf("Candy!\n");
}
关于c - 在命令行参数中查找字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48392272/