【问题标题】:C question: why is my 20 length string limits itself with 6 chars?C 问题:为什么我的 20 长度字符串限制为 6 个字符?
【发布时间】:2020-06-20 03:40:33
【问题描述】:

我正在尝试创建自己的 str_to_upper 函数,但是当我编写超过 5 个字符的内容时,它只返回前 5 个字符和一个 '\0' 字符。 我猜 word[5] 应该是 '\0',这意味着我的代码返回一个 6 字符长度的字符串,但我不明白那个 '\0' 是从哪里来的。

我的代码:

#include <stdio.h>
#include <ctype.h>
#include <string.h>

char *str_to_upper(char *);

int main()
{
    char word[20];

    puts("Please enter a word: ");
    fgets(word, strlen(word), stdin);

    puts(str_to_upper(word));

    return 0;
}

char *str_to_upper(char *sentence)
{
    int length=strlen(sentence);

    for(int i=0; i<length; i++)
    {
        sentence[i]=toupper(sentence[i]);
    }

    return sentence;
}

输出:

Please enter a word: 
aaaaaaaaaaa  
AAAAA

当我在我的数组中写入一个 for 循环时,我得到:

Please enter a word:
aaaaaaaaaaa
AAAAA
AAAAA0��}y

【问题讨论】:

  • 您只能在有效的、以空字符结尾的字符串上使用strlen 来获取其实际长度。这里:fgets(word, strlen(word), stdin)word 未初始化。 fgets 想要它可以填充的缓冲区的大小,所以在这里使用sizeof(word),在你的情况下是20。(不过,你在str_to_upper 中使用strlen 很好。)
  • 旁白:int length=strlen(sentence); for(int i=0; i&lt;length; i++) 两次下降 word。替代方案:for(int i=0; word[i]; i++) 或更好的for(size_t i=0; word[i]; i++)

标签: c string fgets


【解决方案1】:

只需替换你的

fgets(word, strlen(word), stdin);

fgets(word, sizeof(word), stdin);

实际上,strlen 返回一个未初始化的字符串(word)的长度。因此,fgets 的当前限制是您的堆栈中的结果。

【讨论】:

  • 或者不加()简化:fgets(word, sizeof word, stdin);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-03
  • 2015-01-14
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多