Comparing length of two strings entered by the user – CSKC
Sign In

Search

Code Learning #CPP#2565    siteicon   siteicon  

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

TC++ #2565

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

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



Share

Created: 12-Jan-2018 23:44 | Updated: 13-Jan-2018 01:50|