using strcmp

Write a program that reads two strings and specifies if the two strings are equal or which one is smaller (alphabetically). The program then displays the length of each string.


here is my code



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  #include <iostream>
using namespace std;

int main()
{
	char string1[];
	char string2[];
	int result;

	cout << "enter first string: " << endl;
	cin >> string1;

	cout << "enter second string: " << endl;
	cin >> string2;
	
	
	result = strcmp( string1, string2 );
	
	switch( result )
	{
		case ( 1 ):
			cout << "First string is greater than second string " << endl;
			break;
		case ( 0 ):
			cout << "First string is equal to second string " << endl;
			break;
		case ( -1 ):
			cout << "First string is less than second string " << endl;
	}


	cout << "length of first string is: "<< strlen( string1 ) << endl;
    cout << "length of second string is: " << strlen( string2 ) << endl;
	return 0;
}



i need help with reeding the two strings
i think what i did is wrong
Hi,
when declaring the char arrays (string1 & string2) you need to specify the size of array;
 
char string1[20];   //char array (string) of up to 20 characters length 
strcmp() will return zero if the strings are equal but it otherwise it returns a positive or negative number, not necessarily 1 or -1. I'd change your switch statement for something like

1
2
3
4
5
6
7
8
9
10
11
12
if (result > 1)
{
   cout << "First string is greater than second string " << endl;
}
else if ( result == 0)
{
   cout << "First string is equal to second string " << endl;
}
else
{
   cout << "First string is less than second string " << endl;
}

thanks alot
Topic archived. No new replies allowed.