sprintf()与sscanf()

1、sprintf()

sprintf()用于向字符串中写入格式化的数据,eg:

int dSrc1 = 1;
int dSrc2 = 2;
char str[] = "hello";
char buf[100] = { 0 };
sprintf_s(buf, (unsigned)_countof(buf), "%4d,%4d,%s", dSrc1, dSrc2, str);
cout << buf << endl; //输出为 1, 2,hello

_countof:用来计算一个静态分配的数组中的元素的个数,sizeof是用来计算字节数,所需头文件stdlib.h

2、sscanf()

sscanf()用来从字符串中读取格式化的数据到变量或字符数组中,eg:

char*p = "1234abcd";
char buf1[100] = { 0 };
sscanf_s(p, "%s", buf1, (unsigned)_countof(buf1));
cout << buf1 << endl; //输出为1234abcd


char buf2[100] = { 0 };
sscanf_s(p, "%4s", buf2, (unsigned)_countof(buf2));
cout << buf2 << endl; //输出为1234


char strSrc[] = " 1, 2,hello";
int dDest1;
int dDest2;
char buf3[100] = { 0 };
sscanf_s(strSrc, "%4d,%4d,%s", &dDest1, &dDest2, buf3, (unsigned)_countof(buf3));//dDest1:1, dDest2:2, strDest:"hello"
cout << dDest1 << ", " << dDest2 << "," << buf3 << endl;//输出1, 2, hello

原文地址:https://www.cnblogs.com/milanleon/p/5784394.html