The strcmp(string1,string2) function compares string1 to string2. It is a value
ID: 3650992 • Letter: T
Question
The strcmp(string1,string2) function compares string1 tostring2. It is a value returning function that returns a negative integer if
string1 < string2, 0 if string1 == string2, and a positive integer if
string1 > string2. Write a program that reads two names (last name first
followed by a comma followed by the first name) and then prints them in
alphabetical order. The two names should be stored in separate character
arrays holding a maximum of 25 characters each. Use the strcmp() function
to make the comparison of the two names. Remember that 'a' < 'b',
'b' < 'c', etc. Be sure to include the proper header file to use strcmp().
Sample Run 1:
Please input the first name
Brown, George
Please input the second name
Adams, Sally
The names are as follows:
Adams, Sally
Brown, George
Sample Run 2:
Please input the first name
Brown, George
Please input the second name
Brown, George
The names are as follows:
Brown, George
Brown, George
The names are the same
Explanation / Answer
#include
using namespace std;
int main()
{
char string1[];
char string2[];
int result;
cout << "enter first name: " << endl;
cin >> string1;
cout << "enter second name: " << endl;
cin >> string2;
result = strcmp( string1, string2 );
switch( result )
{
case ( 1 ):
cout << " The names are: " << endl;
cout << string2 << endl;
cout << string1 << endl;
break;
case ( 0 ):
cout << "The two names are same " << endl;
cout << string2 << endl;
break;
case ( -1 ):
cout << " The names are: " << endl;
cout << string1 << endl;
cout << string2 << endl;
}
cout << "length of first string is: "<< strlen( string1 ) << endl;
cout << "length of second string is: " << strlen( string2 ) << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.