C++ Program to Implement strncmp() Function
Posted by Superadmin on August 10 2022 13:11:45

C++ Program to Implement strncmp() Function

 

 

This is a C++ Program to Implement strncmp() Function.

Problem Description

The program implements the function strncmp() which compares first ‘n’ characters of two strings.

Problem Solution

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.

C++ Program/Source code

Here is the source code of C++ Program to Implement strncmp() Function. The program output is shown below.

  1. #include<iostream>
  2. using namespace std;
  3. int main ()
  4. {
  5.     char str1[50], str2[50];
  6.     int i, n, flag = 0;
  7.     cout << "Enter string 1 : ";
  8.     gets(str1);
  9.     cout << "Enter string 2 : ";
  10.     gets(str2);
  11.     cout << "Enter number of characters to be compared : ";
  12.     cin >> n;
  13.     for (i = 0; i < n; i++)
  14.     {
  15.         if (str1[i] != str2[i])
  16.         {
  17.             flag = 1;
  18.             break;
  19.         }
  20.     }
  21.     if (flag == 0)
  22.         cout << "Compared strings are equal.";
  23.     else 
  24.         cout << "Strings are not equal.";
  25.     return 0;	
  26. }
Program Explanation

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.

 
Runtime Test Cases
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.