Comparing length of two strings entered by the user
A program to compare length of two strings entered by the user using cin.getline() and compared using strlen.
Learning Objectives
- Calculating length of two user given strings using strlen() and then using selection control to compare length.
Source Code
|
|
Run Output
Code Understanding
char str1[80],str2[80]; //Char array for two strings have been declared here
cout<<“Input string 1: ” ; cin.getline(str1,80);
First string is collected using cin.getline(), so space between words are also allowed.
cout<<endl<<“Input string 2: ” ; cin.getline(str2,80);
Second string is collected here.
int a=strlen(str1),b=strlen(str2); //two variables a and b declared which are initialised with strlen() returned values.
cout<<endl;
if(a>b) cout<<“First string is larger”; //This condition for str1 to be larger
else if(b>a) cout<<“Second string is larger”; //This condition for str2 to be larger
else cout<<“Both strings are same in size”; //Else they must be same
cout<<endl;
Notes
- Sometimes people use strcmp() function with similar objective, but it can only find if the two strings are equal for each character and not for their lengths. You can check other program for strcmp function usage.
Suggested Filename(s): str-comp-len.cpp, slencomp.cpp
Created: 12-Jan-2018 23:44 | Updated: 13-Jan-2018 01:50|
