我正在为一个项目使用 C 样式字符串,但我自己有点困惑。我正在检查字符串以查看它们的前缀是什么(zone_、player_ 等),然后获取字符串的其余部分。
else if(strncmp(info, "zone_", 5) == 0)
{
int len = strlen(info);
char *zoneName = new char[len];
strncpy(zoneName, &info[5], len-5);
Msg("Zone Selected: %s\n", zoneName);
delete zoneName;
}
当我打印出 zoneName 变量时,它是正确的,只是后面跟着一堆乱码。我究竟做错了什么? (我意识到乱码是 char 数组的其余部分为空,但我不知道更好的方法)
最佳答案
参见 strncpy描述:
No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.
关于c++ - strncpy() 获取字符串结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4416132/