Case 1 : Enter string 1 : hi Enter string 2 : hello Enter number of characters to be compared : 1 Compared strings are equal. Case 2 : Enter string 1 : 12345 Enter string 2 : 12345 Enter number of characters to be compared : 5 Compared strings are equal. Case 3 : Enter string 1 : saturday Enter string 2 : SATURDAY Enter number of characters to be compared : 5 String 2 is less than string 1.
Users Online
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Latest Articles
Articles Hierarchy
C++ Program to Implement strncmp() Function
C++ Program to Implement strncmp() Function
This is a C++ Program to Implement strncmp() Function.
The program implements the function strncmp() which compares first ‘n’ characters of two strings.
1. The program takes two strings.
2. Using a for loop, first n characters of the strings are compared.
3. The result is printed accordingly.
4. Exit.
Here is the source code of C++ Program to Implement strncmp() Function. The program output is shown below.
-
#include<iostream>
-
using namespace std;
-
int main ()
-
{
-
char str1[50], str2[50];
-
int i, n, flag = 0;
-
cout << "Enter string 1 : ";
-
gets(str1);
-
cout << "Enter string 2 : ";
-
gets(str2);
-
cout << "Enter number of characters to be compared : ";
-
cin >> n;
-
for (i = 0; i < n; i++)
-
{
-
if (str1[i] != str2[i])
-
{
-
flag = 1;
-
break;
-
}
-
}
-
if (flag == 0)
-
cout << "Compared strings are equal.";
-
else
-
cout << "Strings are not equal.";
-
return 0;
-
}
1. The user is asked to enter two strings and stored in ‘str1’ and ‘str2’.
2. Number of characters to be compared are asked and stored in ‘n’. A temporary variable ‘flag’ is initialized as 0.
3. Using a for loop, first ‘n’ characters of both the strings are compared.
4. If they are not equal, flag is equal to 1 and the loop terminates with break.
5. If flag is equal to 0, then compared strings are equal.
6. Else they are not equal.
7. The result is then printed.