[英]strcat returning wrong character
I am using strcat to build a string. 我正在使用strcat构建字符串。 It works except for when I want to append characters that represent numbers from an array.
除了我要附加表示数组中数字的字符外,它均有效。 The line that uses:
该行使用:
strcat(JsonDataStr, numsToSend[i]);
for example appends the character 'c' instead of '1'. 例如,将字符“ c”代替“ 1”。 If I manually put the character in using double quotes it works, but i want to have a one dimensional array with characters only.
如果我手动将字符放在双引号中,则可以使用,但是我想只包含一个字符的一维数组。
char JsonDataStr[20];
void buildJsonString(){
int offset;
char strtStr[] = "[{\"" ;
char numStr[4];
char numsToSend[4] = {'1', '2','3','4'};
offset = sizeof(strtStr);
strcat(JsonDataStr, strtStr);
for(i = 0 ; i < 2 ; i++){
strcat(JsonDataStr, JsonDataName);
ByteToStr(i, numStr);
strcat(JsonDataStr, numsToSend[i]);
strcat(JsonDataStr, "\":\"");
}
strcat(JsonDataStr, "\"}]");
}
Any idea why this is happening. 知道为什么会这样。
You can't use strcat
like this. 您不能像这样使用
strcat
。 It appends strings to strings, not single chars to strings. 它将字符串追加到字符串,而不是单个字符追加到字符串。 A quick fix would be to have
numsToSend
as an array of char pointers instead: 一个快速的解决方法是将
numsToSend
作为char指针的数组代替:
char *numsToSend[4] = { "1", "2", "3", "4" };
Other than that you could write a function that appends chars to strings, see this answer for an example. 除此之外,您可以编写一个附加字符为字符串的函数,看到这个答案的一个例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.