gpt4 book ai didi

c - 请帮助我了解 "strcmp"

转载 作者:行者123 更新时间:2023-11-30 21:48:42 27 4
gpt4 key购买 nike

我有一段 C 代码,我想在输入一些字符串(例如“up”)时询问。跳转到代码如下:(strcmp(pdirection,"up")==0)
那么,什么意思呢,我特别不明白==0

代码片段是通过引用位置调用的。

最佳答案

来自manual

int strcmp(const char *s1, const char *s2);

The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

因此,如果两个字符串相等,则 strcmp() 返回 0

== 是等于运算符,它检查两边的值是否相等。让我们看看 C 标准怎么说

6.5.9

equality-expression == relational-expression

3 The == (equal to) and != (not equal to) operators are analogous to the relational operators except for their lower precedence.108) Each of the operators yields 1 if the specified relation is true and 0 if it is false. The result has type int. For any pair of operands, exactly one of the relations is true.

您的代码可能是

if( strcmp(pdirection,"up") == 0 )
do_something;

因此,如果 pdirection 中存储的字符串等于 "up",则函数 strcmp() 将返回 0,并且== 0 部分检查该值是否等于 0,如果等于 0,则完成 do_something

关于c - 请帮助我了解 "strcmp",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29985836/

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