I am writing a program to simulate strcmp(). This is my code.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 100
int strcmp(const char *str1, const char *str2);
char s1[MAX], s2[MAX];
int main()
{
printf("Compare two user entered strings character by character.\n");
printf("Enter string one: ");
fgets(s1, MAX, stdin);
printf("Enter string two: ");
fgets(s2, MAX, stdin);
printf("The user entered string one is: %s", s1);
printf("The user entered string two is: %s", s2);
printf("The value returned by strcmp() is: %d", strcmp(s1, s2));
return 0;
}
int strcmp(const char *str1, const char *str2){
int result;
while(*str1 != '\0' && *str1 - *str2 == 0){
str1++;
str2++;
}
if(*str1 - *str2 != '\0'){
printf("%d\n", *str1);
printf("%d\n", *str2);
result = *str1 - *str2;
}else if(*str1 == '\0' && *str2 == '\0'){
result = 0;
}
return result;
}
It works fine for the most part and the strcmp() function returns the correct results, except for when one string terminates and the other has characters left. I use the while loop to compare the characters and increment the pointers to the next character. When a string is incremented to '\0' the integer value displayed on doing a printf is 10. Why isn't it 0? Because the value is 10, deducting other strings' character from it gives a result which is larger by 10.
Why does this happen?
The function fgets
can append the new line character '\n'
- decimal 10
(that corresponds to the key Enter) to the entered string if there is enough space in the destination character array.
You should remove it. For example
#include <string.h>
//...
fgets(s1, MAX, stdin);
s1[ strcspn( s1, "\n" ) ] = '\0';
printf("Enter string two: ");
fgets(s2, MAX, stdin);
s2[ strcspn( s2, "\n" ) ] = '\0';