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.
Try this simple code.
#include <stdio.h>
#include <string.h>
int my_strlen(char *string) //Function to calculate length of given string
{
int i;
for(i=0;string[i]!='\0';i++);
return i;
}
int main(int argc, char *argv[])
{
int length;
if(argc != 2) //Check the number of command line arguments
{
printf("You must run this program with an argument\n");
return 2;
}
else
{
length = my_strlen(argv[1]); //Your function to calculate length of string
printf("Length of command line argument is: %d\n", length);
}
return 0;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments