-4

Here is my code:

#include<stdio.h>
#include<string.h>
int string_length(char s[]);
main()
{
        char s[50];
        int l;
        printf("Enter the string\n");
        scanf("%s\n",s);
        l=strlen(s);
        printf("Length of string = %d\n",l);
}
int string_length(char s[])
{
        int i;
        i=0;
        while(s[i] != '\0')
                ++i;
                return i;

}

After compile it scan for two input values.

What's wrong with my code?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Jashid
  • 9
  • 1
  • 2
  • 7
  • You did receive an answer in your previous post http://stackoverflow.com/questions/5685497/using-recursion-to-find-the-length-of-a-string-in-c - Why do you repaste that exact same question? – halfdan Apr 16 '11 at 10:09

5 Answers5

7

Get rid of the newline in the scanf.

scanf("%s",s);

That should get this code to work.

But I am unable to understand why you wrote a function to compute string length if you had to use strlen().

HTH,
Sriram.

Sriram
  • 10,298
  • 21
  • 83
  • 136
1
const size_t sillyStrlen(const char* text) {
  if (*text) {
    return sillyStrlen(text + 1) + 1;
  }
  return 0;
}
Jim Blackler
  • 22,946
  • 12
  • 85
  • 101
  • i think adding '\0' meant that there is no limit for string.Right? – Jashid Apr 16 '11 at 09:20
  • 1
    @Jashin: Your test for '\0' is the same as Jim's test (*text), both test for null. – forsvarir Apr 16 '11 at 09:34
  • Just posting the code for a homework question isn't a great way to help the OP learn. You might want to have a look at http://stackoverflow.com/questions/3937007/problem-with-recursion which had a great answer for a homework recursion problem. – forsvarir Apr 16 '11 at 09:36
  • 1
    You want to return a `size_t` instead of a `const char *`. – pmg Apr 16 '11 at 13:57
1

You're calling strlen instead of your own string_length in main.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
0
  1. Buy a book, see The Definitive C Book Guide and List
  2. Read about the language syntax
  3. Learn how to use pointers
  4. You've just learned how to write a int strlen(char[]) function.
Community
  • 1
  • 1
Lekensteyn
  • 64,486
  • 22
  • 159
  • 192
0

Try This one.

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
   {
    char *str;
    printf("Enter a string\n");
    gets(str);
    printf("The size of the string is %d",strlen(str));
    getch();
    return 0;
    }
Brad Larson
  • 170,088
  • 45
  • 397
  • 571