c - 在命令行参数中查找字符串?

标签 c

我目前正在开发一个 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/

相关文章:

从文件未定义行为打印的 C 行

c - 不使用 ebp 实现堆栈回溯

在 C 中复制不确定的指针

c - 如何比较两个字符串的If值?

c - 使用 libpcsclite 开发错误编译(未定义)

c++ - 等价于 C 中的 std::aligned_storage<>?

c - 我的 C 程序如何检查它是否对给定文件具有执行权限?

c - JNI : undefined symbol GOMP_parallel

c - 在 ARM macOS 上,当显式 raise() 信号时,某些返回地址在堆栈上会出现乱码

c - 如何编写一个原型(prototype)为 'void convertstring(char *)' 的函数,在 C 中将小写字母转换为大写字母?