Close
Close

Displaying the length of a user-entered function

   Ben

So my code is:

 

#include<stdio.h>
#include<string.h>
int main()
{
    char name[25];
    int length;
    length = strlen(name);
    printf("Enter your name.\n");
    gets(name);
    printf("The length of your name is %d", length);
    return 0;
}

 

But the output only returns “1” no matter how many characters I put, wha have I done incorrectly?

  • I meant displaying the length of a user entered STRING***
    - Ben

Answers

  •   
    #include<stdio.h>
    #include<string.h>
    int main()
    {
        char name[25];
        int length;
        //You have not given any value to the variable name
        //So, the value here is 0
        //length = strlen(name);
        printf("Enter your name.\n");
        gets(name);
        //Now your variable has a value
        //So, you can calculate the length of it.
        length = strlen(name);
        printf("The length of your name is %d", length);
        return 0;
    }
    

     


    • I’m confused, how does your answer differ from mine, aside from where you define the value of length, isn’t it the same code? And since I define length before I print it, why does it matter?
      - Ben
    • Ohhhhh I get it now, because name doesn’t have a value before I define length, because I define length before I get the value of name, the value of length remains zero, is that correct?
      - Ben
    • Yes.
      - Amit Kumar

Ask Yours
Post Yours
Write your answer