Search code examples
ccommand-line-argumentsargvstrlen

How to count the number of characters in a command line argument by using and creating a function


I am having trouble understanding how to create a function to count the characters in a command line argument. It only has to compute the result in the 'my_strlen()' function, but to print the result out in main(). I am very new to C, but here is my code so far;

int my_strlen(  char string[]);
{
     strcpy(string, argv[1];
     return 1;
}
int main(int argc, char *argv[])
{
  if(argv != 2)
  {
    printf("You must run this program with an argument\n");
    return 2;
  }
  printf("%d", strlen(string);
  return 0;
}

So as you can see, I am pretty confused, I also didn't know how to store the value of strlen(string) to call it later as its own integer.


Solution

  • Try this simple code.

    #include <stdio.h>
    #include <string.h>
    
    /* Function to calculate length of given string */
    int my_strlen(char *input_string)
    {
        /* Loop through all the characters in the string till null-terminator */
        int i;
        for(i=0; input_string[i] != '\0'; i++);
        return i;
    }
    
    int main(int argc, char *argv[])
    {
      int length = -1;
      if(argc != 2) /* Check the number of command line arguments */
      {
        printf("You must run this program with an argument\n");
        return 2;
      }
      else
      {
        /* Your function to calculate length of the string */
        length = my_strlen(argv[1]); 
        printf("Length of command line argument is: %d\n", length);
      }
      return 0;
    }
    

    Here
    argv[0] is program name.
    argv[1] is the argument to the program.