📜  C++ memcmp()

📅  最后修改于: 2020-09-25 09:04:13             🧑  作者: Mango

C++中的memcmp() 函数比较两个指针对象的指定数量的字符

memcmp()原型

int memcmp( const void* lhs, const void* rhs, size_t count );

memcmp() 函数采用三个参数: lhsrhscount 。此函数首先将lhsrhs指向的对象解释为unsigned char数组。然后按字典顺序比较lhsrhs的第一个count 字符 。

它在头文件中定义。

memcmp()参数

memcmp()返回值

memcmp() 函数返回:

示例:memcmp() 函数的工作方式

#include 
#include 

using namespace std;

void display(char *lhs, char *rhs, int result, int count)
{
    if(result > 0)
        cout << rhs << " precedes " << lhs << endl;
    else if (result < 0)
        cout << lhs << " precedes " << rhs << endl;
    else
        cout << "First " << count << " characters of " << lhs << " and " << rhs << " are same" << endl;
}

int main()
{
    char lhs[] = "Hello World!";
    char rhs[] = "Hello Earth!";
    int result;

    result = memcmp(lhs, rhs, 5);
    display(lhs, rhs, result, 5);
    
    result = memcmp(lhs, rhs, 7);
    display(lhs, rhs, result, 7);
    return 0;
}

运行该程序时,输出为:

First 5 characters of Hello World! and Hello Earth! are same
Hello Earth! precedes Hello World!