概述
snprintf
,strcpy
,strncpy
这几个函数的功能都是将原字符串拷贝到目的字符串中。但是在细节部分还是存在着一些细微的差别。主要参考man
说明。
snprintf
格式
int snprintf(char *str, size_t size, const char *format, ...);
说明
The functions snprintf() and vsnprintf() write at most size bytes (including the terminating null byte (‘\0’)) to str.
即,snprintf
会把源字符串拷贝到目的地址。如果源字符串的长度大于约束条件size
,那么会拷贝size - 1
个字符到目的地址,并将最后一个字符赋值为'\0'
。
例子
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char buf[10] = {0};
snprintf(buf, 10, "hello word");
cout << buf << ", " << strlen(buf) << ", " << sizeof(buf