繁体   English   中英

C char to string(将char传递给strcat())

[英]C char to string (passing char to strcat())

我的问题是将char转换为字符串我必须传递给strcat()一个字符串附加到字符串,我该怎么办? 谢谢!

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

char *asd(char* in, char *out){
    while(*in){
        strcat(out, *in); // <-- err arg 2 makes pointer from integer without a cast
        *in++;
    }
    return out;
}

int main(){
    char st[] = "text";
    char ok[200];
    asd(st, ok);
    printf("%s", ok);
    return 0;
}

由于ok指向未初始化的字符数组,因此它们都是垃圾值,因此串联(通过strcat )将在何处开始是未知的。 strcat采用C字符串(即由'\\ 0'字符终止的字符数组)。 char a[200] = ""会给你一个[0] ='\\ 0',然后[1]到[199]设置为0。

编辑:(添加了更正的代码版本)

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

char *asd(char* in, char *out)
{

/*
    It is incorrect to pass `*in` since it'll give only the character pointed to 
    by `in`; passing `in` will give the starting address of the array to strcat
 */

    strcat(out, in);
    return out;
}

int main(){
    char st[] = "text";
    char ok[200] = "somevalue"; /* 's', 'o', 'm', 'e', 'v', 'a', 'l', 'u', 'e', '\0' */
    asd(st, ok);
    printf("%s", ok);
    return 0;
}

strcat不会附加单个字符。 相反,它需要一个const char* (一个完整的C风格的字符串),它附加在第一个参数的字符串中。 所以你的函数应该是这样的:

char *asd(char* in, char *out)
{
    char *end = out + strlen(out);

    do
    {
        *end++ = *in;

    } while(*in++);

    return out;
}

do-while循环将包括在C样式字符串结尾处必需的零终止符。 确保您的out字符串在结尾处使用零终止符进行初始化,否则此示例将失败。

除此之外:想想*in++; 确实。 这将增加in和取消对它的引用,这是非常相同in++ ,所以*是没用的。

为了查看你的代码,我可以提出一些与之相关的指示,这不是一个批评,用一点盐来实现,这将使你成为一个更好的C程序员:

  • 没有功能原型。
  • 指针使用不正确
  • 处理strcat函数使用不正确。
  • 过度使用 - 不需要asd功能本身!
  • 处理变量的用法,特别是未正确初始化的char数组。
#include <stdio.h>
#include <string.h>

int main(){
    char st[] = "text";
    char ok[200];
    ok[0] = '\0'; /* OR
    memset(ok, 0, sizeof(ok));
    */
    strcat(ok, st);
    printf("%s", ok);
    return 0;
}

希望这会有所帮助,最好的问候,汤姆。

要将字符转换为(空终止)字符串,您可以简单地执行以下操作:

char* ctos(char c)
{
    char s[2];
    sprintf(s, "%c\0", c);
    return s;
}

工作示例: http//ideone.com/Cfav3e

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM