How to prevent my code to count `\0` as one character?

39 Views Asked by At

I'm attempting to make strlen in C standard library on my own.
Following is my code and the strlen func I made is given the name mystrlen in the script below.

   #include <stdio.h>
  
   //int mystrlen(const char* str);
  
   int mystrlen(const char* str){
           int i;
           for (i=0;str[i]!='\0';i++);
           return i;
  }
 
 
  int main(void){
          char input[100];
          fgets(input,sizeof input, stdin);
          printf("The length of your string : %d\n", mystrlen(input));     
          return 0;
  }                        

However, when I executed the compiled code, the output always shows the length of input string one greater than its actual size.

Example: (input is abc)

abc
The length of your string : 4

I think this is because my code counts '\0', the last character in the string as one character. I have searched for the Internet about how to avoid count the NULL character, but I didn't find any useful info.

Could you please tell me how to solve this problem? Thank you.

0

There are 0 best solutions below