-5

Does it not return an int or something? This is a snippet of my code:

int wordlength(char *x);

int main()
{
    char word;
    printf("Enter a word: \n");
    scanf("%c \n", &word);
    printf("Word Length: %d", wordlength(word));
    return 0;
}

int wordlength(char *x)
{
    int length = strlen(x);
    return length;
}
Evyione
  • 31
  • 2
  • 10
  • 5
    A `char` is not a string... – Oliver Charlesworth Oct 12 '14 at 21:36
  • but I read that strlen wants a char as an argument. So, wordlength wants a char of x. When the user puts in a word, it'll be considered as a char. Also, my professor told us to put when using strlen. – Evyione Oct 12 '14 at 21:40
  • @Evyione: no, `strlen` needs a `char *` (actually a `const char *`), not just a `char`. – Paul R Oct 12 '14 at 21:42
  • 1
    You might want to read the [tag:string] [tag-wiki](https://stackoverflow.com/tags/string/info). – Deduplicator Oct 12 '14 at 21:54
  • "I read that strlen wants a char as an argument" -- No, you did not read that ... and it doesn't make sense. "So, wordlength wants a char of x" -- No, it wants a pointer to char ... which is what you gave it, but the point is that `word` is only 1 char long. You need to make it an array of chars, big enough to hold any word you expect to read. – Jim Balter Oct 18 '14 at 21:03

2 Answers2

1

Change this part:

char word;
printf("Enter a word: \n");
scanf("%c \n", &word);

to:

char word[256];       // you need a string here, not just a single character
printf("Enter a word: \n");
scanf("%255s", word); // to read a string with scanf you need %s, not %c.
                      // Note also that you don't need an & for a string,
                      // and note that %255s prevents buffer overflow if
                      // the input string is too long.

You should also know that the compiler would have helped you with most of these problems if you had enabled warnings (e.g. gcc -Wall ...)


Update: For a sentence (i.e. a string including white space) you would need to use fgets:
char sentence[256];
printf("Enter a sentence: \n");
fgets(sentence, sizeof(sentence), stdin);
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • I tried putting a sentence, and it doesn't count whitespace? – Evyione Oct 12 '14 at 21:48
  • 1
    That's correct - the code above accepts a "word", as implied by your buffer name. For a sentence you would need to use `fgets` (see edit above). – Paul R Oct 12 '14 at 21:49
1

Function strlen is applied to strings (character arrays) that have the terminating zero. You are applying the function to a pointer to a single character. So the program has undefined behaviour.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335