strcmp() 在 C 中究竟返回什么? [英] What does strcmp() exactly return in C?

查看:45
本文介绍了strcmp() 在 C 中究竟返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 C 编写了这段代码:

#include #include #include #include int main(){字符字符串1[20];字符字符串2[20];strcpy(string1, "Heloooo");strcpy(string2, "Helloo");printf("%d", strcmp(string1, string2));返回(0);}

控制台应该打印值 1 还是 o\0 字符的 ASCII 值之间的差异,即 111?在这个网站上,写到这应该给出 put 111,但是当我运行时在我的笔记本电脑上,它显示 1.为什么?

解决方案

来自 cppreference.com 文档

<块引用>

int strcmp( const char *lhs, const char *rhs );

返回值

  • 如果 lhs 按字典顺序出现在 rhs 之前,则为负值.

  • 如果 lhs 和 rhs 比较相等则为零.

  • 如果 lhs 按字典顺序出现在 rhs 之后,则为正值.

正如您所见,它只是表示负数、零或正数.你不能指望别的.

您链接的网站没有错误.它告诉你返回值是 <0, == 0>0 它给出了一个例子并显示了它的输出.它没有告诉输出应该是 111.

I wrote this code in C:

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

int main()
{
    char string1[20];
    char string2[20];
    strcpy(string1, "Heloooo");
    strcpy(string2, "Helloo");
    printf("%d", strcmp(string1, string2));
    return(0);
}

Should console print value 1 or difference between ASCII values of o and \0 character i.e. 111? On this website, it is written that this should give out put 111, but when I run it on my laptop, it shows 1. Why?

解决方案

From the cppreference.com documentation

int strcmp( const char *lhs, const char *rhs );

Return value

  • Negative value if lhs appears before rhs in lexicographical order.

  • Zero if lhs and rhs compare equal.

  • Positive value if lhs appears after rhs in lexicographical order.

As you can see it just says negative, zero or positive. You can't count on anything else.

The site you linked isn't incorrect. It tells you that the return value is < 0, == 0 or > 0 and it gives an example and shows it's output. It doesn't tell the output should be 111.

这篇关于strcmp() 在 C 中究竟返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆