【问题标题】:Having some trouble with string.h library in CC 中的 string.h 库有一些问题
【发布时间】:2021-10-21 14:28:17
【问题描述】:

我已经在 C 中运行了这段代码,

char *bracket_by_len(char *output, char *word, int length)
{
    if(strlen(word) < 5) {
        output[0] = '<';
        output[1] = '<';

        /*int i = 2;
        while(i != (strlen(word) + 2)) {
            output[i] = word[i - 2];
            i += 1;
        }*/

        strncat(output, word, strlen(word));
        strcat(output, ">>");
return output;
} else {... not using them as 4 letter word for input}

int main()
{
    char word[40], output[40]; // word is not used.
    printf("%s \n.", bracket_by_len(output, "word", 20);
    return 0;
}

实际代码是这样的:Input code. 然后我写了

return output;

我用这个打印出来的

printf("Based on size, \t %s.\n", output);

输出如下:

Based on size, <<^S>>.

开头有一些随机字符。当我将 strncat() 函数替换为 while 循环并手动复制单词的字母时,输入没问题。

提前致谢。

【问题讨论】:

  • 输出和字是如何定义的?
  • output 是如何声明和初始化的?请发帖minimal reproducible example
  • 你能展示整个代码吗?为什么从output[1]而不是output[0]开始?
  • output[2] = 0; 丢失,需要生成一个以零结尾的字符串。 strcpy(output, "&lt;&lt;"); 更有意义。
  • @shrewmouse,“新人”不是借口。如果他是新来的,他应该阅读How do I ask a good question?。 Downvotes 确实反映了问题的质量或有用性,并且不是个人的。顺便说一句,它甚至不消耗声望,因为你不能低于 1。

标签: c c-strings


【解决方案1】:

output 没有被 NULL 终止。在左边的人字形之后添加它。

output[0] = '<';
output[1] = '<';
output[2] = 0;
strncat(output, word, strlen(word));
printf("%s\n", output);

如果您改用sprintf,则不必担心添加该详细信息的空值。

sprintf(output, "<<");
strncat(output, word, strlen(word));
printf("%s\n", output);

【讨论】:

  • 我确实尝试过。我错误地写了输出[1]。对不起。
  • 根据您的输出,我认为word 的第一个字符没有被初始化
  • 不,我将命令作为函数传递(输出,“word”,20);
  • 循环遍历outputword 并将每个字符打印为整数printf("%d\n",output[i])。您将能够找到违规字符的值。 ^S 可能是单个字符。
  • 当我做循环时,我得到了预期的完美输出。
猜你喜欢
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-26
  • 2011-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多