-1

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?

ra5
  • 11
  • 2

1 Answers1

2

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'; 
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • That's a neat way to do it. Thank you. `scanf(" %[^\n]",s1)` does the job as well. Many ASCII charts don't have the newline character listed. Found one now with it listed. [link](https://1.bp.blogspot.com/-1DARuE2wyUc/XIPF_1CisdI/AAAAAAAAAh8/frDwPTIhG94f9ciKx514duPPD4n2PRTHQCLcBGAs/s1600/Ascii.png) – ra5 Feb 05 '20 at 16:11
  • @ra5 Here is one drawback. If you need to read several strings you need in any case to remove the new line character from the input buffer before a next read. – Vlad from Moscow Feb 05 '20 at 16:19