Write a function which takes two string variables (not C strings) as inputs and
ID: 655219 • Letter: W
Question
Write a function which takes two string variables (not C strings) as inputs and compares them. If they are equal, the function should return 0. If the first string is less than the second string, return a negative number. If the first string is greater than the second string, return a positive number. You are not allowed to use the compare method of the stringdata type. You must use the comparison operators. Do not write a main function. Your function does not do any cin or cout. Make sure to properly format all your code in C++.
Explanation / Answer
The strcmp() function compares two strings and returns an integer as a result of its comparison. Its syntax is:
int strcmp(const char* S1, const char* S2);
This function takes two strings, S1 and S2 and compares them. It returns
A negative value if S1 is less than S2
0 if S1 and S2 are equal
A positive value if S1 is greater than S2
#include <iostream>
using namespace std;
int main()
{
char *FirstName1 = "Andy";
char *FirstName2 = "Charles";
char *LastName1 = "Stanley";
char *LastName2 = "Stanley";
int Value1 = strcmp(FirstName1, FirstName2);
int Value2 = strcmp(FirstName2, FirstName1);
int Value3 = strcmp(LastName1, LastName2);
cout << "The result of comparing " << FirstName1
<< " and " << FirstName2 << " is " << Value1 << endl;
cout << "The result of comparing " << FirstName2
<< " and " << FirstName1 << " is " << Value2 << endl;
cout << "The result of comparing " << LastName1
<< " and " << LastName2 << " is " << Value3;
return 0;
}
This would produce:
The result of comparing Andy and Charles is -2
The result of comparing Charles and Andy is 2
The result of comparing Stanley and Stanley is 0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.