Technology Programming

How to Use the Strcmp Function in C++

Instructions

1

Learn the syntax of strcmp in C++. The complete syntax is int strcmp (const char pointer1, const char pointer2);.
2

Notice that pointer1 and pointer2 are pointers to characters. Strcmp starts at the beginning of each string and begins comparing characters until they differ, or a null terminating character is read. If the bytes all match, strcmp returns zero. If the first non-matching byte as an unsigned char is greater for pointer1, strcmp returns a positive integer; otherwise, it returns a negative integer.
3

Understand that the C++ strcmp function is kept in the cstring library. You may need to include the string.h header file to use this function.
4

Look at the following complete program for some simple examples of how to use strcmp:

include 5

Observe the following output for this program:

What is my name? Jane
What is my name? john
What is my name? John
That's right!

Notice that this program continues to solicit input until the user enters "John". "john" is not a match because an upper and lower case "J" have different byte values.


Leave a reply