【发布时间】:2016-08-05 15:13:51
【问题描述】:
这是我用来从char数组构造字符串的演示代码,有没有更好的方法来构造字符串*RV200#*FV200#??
int main()
{
char String4H1[10] = "*FV";
char String4H3[10] = "*RV";
char String4H2[10] = "#";
char data1[10];
char data2[10];
snprintf(data1,4, "%03d", 200); //Convert integer to string function
snprintf(data2,4, "%03d", 200); //Convert integer to string function
ConvertToString(String4H1,data1, 3); //*FV200
ConvertToString(String4H3,data2, 3); //*RV200
ConvertToString(String4H1,String4H2,6); //*FV200#
ConvertToString(String4H3,String4H2,6); //*RV200#
//Display String4H1 And String 4H3
}
void ConvertToString(char subject[], const char insert[], int pos)
{
char buf[100] = {};
strncpy(buf, subject, pos); // copy at most first pos characters
int len = strlen(buf);
strcpy(buf+len, insert); // copy all of insert[] at the end
len += strlen(insert); // increase the length by length of insert[]
strcpy(buf+len, subject+pos); // copy the rest
strcpy(subject, buf); // copy it back to subject
// deallocate buf[] here, if used malloc()
}
数字200在程序开始时是未知的,它是使用IDE函数从内存中获取的,以从特定的内存地址获取值。
像这样:-
unsigned short BUF = GetWord(@FrontVIB@,0);
unsigned short BUF1 = GetWord(@RearVIB@,0);
//BUF and BUF1 stores the value of address @FrontVIB@ and @RearVIB@ respectively
**structure** :-
unsigned short GetWord( @Address Alias@, Address Offset );
【问题讨论】:
-
为什么不对整个字符串使用
snprintf?喜欢snprintf(data1, sizeof(data1), "%s%d%s", String4H1, 200, String4H2);? -
@JoachimPileborg
"%s%d%s"应该是"%s%03d%s" -
snprintf(data1,sizeof(data1), "%s%03d#", String4H1, 200); -
char String4H1[] = "*FV";其他人也一样 -
char buf[100] = {};你确定这应该是C?