【问题标题】:strlen doesn't work even with #include <string.h> in Cstrlen 即使在 C 中使用 #include <string.h> 也不起作用
【发布时间】:2014-10-12 21:34:26
【问题描述】:

它不返回一个 int 或其他东西吗? 这是我的代码的 sn-p:

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

【问题讨论】:

  • A char 不是字符串...
  • 但我读到 strlen 想要一个 char 作为参数。因此,wordlength 需要 x 的字符。当用户输入一个单词时,它将被视为一个字符。另外,我的教授告诉我们在使用 strlen 时输入
  • @Evyione: 不,strlen 需要char *(实际上是const char *),而不仅仅是char
  • 您可能想阅读stringtag-wiki
  • “我读到 strlen 想要一个 char 作为参数”——不,你没有读到……而且它没有意义。 “所以,wordlength 想要一个 x 的字符”——不,它想要一个指向 char 的指针……这就是你给它的,但关键是 word 只有 1 个字符长。你需要把它变成一个字符数组,大到足以容纳你希望阅读的任何单词。

标签: c strlen string.h


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    改变这部分:

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

    【讨论】:

    • 我试着放一个句子,它不算空格?
    • 这是正确的 - 上面的代码接受一个“单词”,正如您的缓冲区名称所暗示的那样。对于一个句子,您需要使用fgets(参见上面的编辑)。
    猜你喜欢
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 2023-04-09
    • 2021-07-08
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多