一个关于字符串拼接的问题
本帖最后由 antiMight 于 2012-12-22 10:27:29 编辑 我用strncpy和strncat来拼接字符串,第一种是直接多次调用,第二种是串接调用,应该效率高点,看起来两个结果应该是一样的才对,但是第二个输出结果有问题,我知道是tbuf的问题,把三个调用tbuf的地方换成三个就是对的,但是为什么呢?这两种方式应该是一样的吧?不一样的只是第二个cat时是直接从上一次的结尾赋值,即使我在_itoa里用了相同的tbuf,strncat后不是会直接拷贝的吗?拷贝完应该就是正确的到buf里了才对吧,谁来解释下?
char tbuf[4] = {0};
char buf[1024] = {0};
strncpy(buf, "\n", 2);
strncat(buf, _itoa(1, tbuf, 10), 3);
strncat(buf, ":", 2);
strncat(buf, _itoa(2, tbuf, 10), 3);
strncat(buf, ":", 2);
strncat(buf, _itoa(3, tbuf, 10), 3);
strncat(buf, "\n", 2);
std::cout << buf<< std::endl;//1:2:3
strncat(strncat(strncat(strncat(strncat(strncat(
strncpy(buf, "\n", 2),
_itoa(1, tbuf, 10), 3),
":", 2),
_itoa(2, tbuf, 10), 3),
":", 2),
_itoa(3, tbuf, 10), 3),
"\n", 2);
std::cout << buf<< std::endl;//1:1:1
char tbuf[4] = {0};
char buf[1024] = {0};
strncat(buf, _itoa(1, tbuf, 10), 3);
strncat(buf, _itoa(2, tbuf, 10), 3);
buf[0] = 0;
strncat(strncat(buf, _itoa(1, tbuf, 10), 3), _itoa(2, tbuf, 10), 3);