即使在C </string.h>中使用#include <string.h>,strlen也不起作用

时间:2014-10-12 21:34:26

标签: c strlen string.h

它不会返回int或者什么东西吗? 这是我的代码片段:

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;
}

2 个答案:

答案 0 :(得分:1)

更改此部分:

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

为:

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.

如果您启用了警告(例如gcc -Wall ...),您还应该知道编译器会帮助您解决大多数这些问题

<小时/> 更新:对于一个句子(即包含空格的字符串),您需要使用fgets

char sentence[256];
printf("Enter a sentence: \n");
fgets(sentence, sizeof(sentence), stdin);

答案 1 :(得分:1)

函数strlen应用于具有终止零的字符串(字符数组)。您正在将该函数应用于指向单个字符的指针。所以程序有不确定的行为。

相关问题