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

时间:2010-02-27 13:24:19

标签: c string char strcat

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

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

4 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:3)

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++非常相似,因此*无用。

答案 2 :(得分:2)

要查看你的代码,我可以提出一些与之相关的指示,这不是一个批评,用一点点盐来实现,这将使你成为一个更好的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;
}

希望这有帮助, 最好的祝福, 汤姆。

答案 3 :(得分:0)

要将字符转换为(空终止)字符串,您只需执行以下操作:

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

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

相关问题