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.
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.
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Practice Computer Science MCQs
- Buy C++ Books
- Apply for C++ Internship
- Practice Programming MCQs
- Buy Programming Books