简体   繁体   English

将int作为char添加到char []

[英]Adding int as a char to a char[ ]

Sorry if the topic name isn't very clear I couldn't find a way to express it. 很抱歉,如果主题名称不是很清楚,我找不到表达它的方法。 So let's say i have this structure : 所以说我有这个结构:

    struct filee 
    {
       ...
       int number;
       char filename[7];
    };
typedef struct filee filee;

and I want to initialize it with a function 我想用一个函数初始化它

void file_init(filee* x,int n)
{
    x->number=n;
    x->filename=(char)n+"ch.bmp"
}

but that doesn't really work so what I want is if for example I do this : 但这并没有真正起作用,所以我想要的是例如,如果我这样做:

file_init(&randomFile,2);

It works this way: 它是这样工作的:

randomFile.number=2;
randomFile.filename="2ch.bmp";

I hope that what I said is clear and thanks for the help! 我希望我所说的清楚,并感谢您的帮助!

You need to use snprintf() 您需要使用snprintf()

int length;
int result;

length = sizeof(x->filename);
result = snprintf(x->filename, length, "%dch.bmp", x->number);
if ((result < 0) || (result >= length))
    error_TheTargetIsNotLargeEnough();

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

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