當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ std::memcmp()用法及代碼示例


它比較buf1和buf2指向的數組的第一個計數字符。
用法:

int memcmp(const void *buf1, const void *buf2, size_t count);
返回值: it returns an integer.
參數:  
buf1: Pointer to block of memory.
buf2: Pointer to block of memory.
count: Maximum numbers of bytes to compare.
Return Value is interpreted as:
Value                                Meaning
Less than zero                       buf1 is less than buf2.
Zero                                 buf1 is equal to buf2.
Greater than zero                    buf1 is greater than buf2.

例子1.當計數大於零(> 0)

// CPP program to illustrate std::memcmp() 
#include <iostream> 
#include <cstring> 
  
int main() 
{ 
    char buff1[] = "Welcome to GeeksforGeeks"; 
    char buff2[] = "Hello Geeks "; 
  
    int a; 
  
    a = std::memcmp(buff1, buff2, sizeof(buff1)); 
  
    if (a > 0) 
        std::cout << buff1 << " is greater than " << buff2; 
    else if (a < 0) 
        std::cout << buff1 << "is less than " << buff2; 
    else
        std::cout << buff1 << " is the same as " << buff2; 
  
    return 0; 
}

輸出:


Welcome to GeeksforGeeks is greater than Hello Geeks 

例子2.當計數小於零(<0)

// CPP program to illustrate std::memcmp()  
#include <cstring> 
#include <iostream> 
  
int main() 
{ 
    int comp = memcmp("GEEKSFORGEEKS", "geeksforgeeks", 6); 
    if (comp == 0) { 
        std::cout << "both are equal"; 
    } 
    if (comp < 0) { 
        std::cout << "String 1  is less than String 2"; 
    } else { 
        std::cout << "String 1 is  greater than String 2"; 
    } 
}

輸出:

String 1 is less than String 2

示例3:當計數等於零(= 0)時

// CPP program to illustrate std::memcmp() 
#include <iostream> 
#include <cstring> 
  
int main() 
{ 
    char buff1[] = "Welcome to GeeksforGeeks"; 
    char buff2[] = "Welcome to GeeksforGeeks"; 
  
    int a; 
  
    a = std::memcmp(buff1, buff2, sizeof(buff1)); 
  
    if (a > 0) 
        std::cout << buff1 << " is greater than " << buff2; 
    else if (a < 0) 
        std::cout << buff1 << "is less than " << buff2; 
    else
        std::cout << buff1 << " is the same as " << buff2; 
  
    return 0; 
}

輸出:

Welcome to GeeksforGeeks is the same as Welcome to GeeksforGeeks


相關用法


注:本文由純淨天空篩選整理自 std::memcmp() in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。