-5

它不返回一个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;
}
4

2 回答 2

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);
于 2014-10-12T21:37:26.100 回答
1

函数strlen应用于以零结尾的字符串(字符数组)。您正在将该函数应用于指向单个字符的指针。所以程序有未定义的行为。

于 2014-10-12T21:40:27.787 回答