A program to find length of string
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?
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.
You're calling strlen
instead of your own string_length
in main
.
const size_t sillyStrlen(const char* text) {
if (*text) {
return sillyStrlen(text + 1) + 1;
}
return 0;
}
- Buy a book, see The Definitive C Book Guide and List
- Read about the language syntax
- Learn how to use pointers
- You've just learned how to write a
int strlen(char[])
function.
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; }
精彩评论