在网上查资料看到这样一句话:
作为一个C程序员,对 scanf,sscanf,fscanf,printf,sprintf,fprintf这类函数的用法,还是要做到“拳不离手,曲不离口”的。
我们在做嵌入式程序开发的时候,对于这些函数的应用需求特别强烈。 可以提高我们的程序效率。
所以特意做了以下整理, 函数功能在注释里面有介绍, 最后附运行结果, 可以比对着看, 更好理解。
int main()
{
int key1, key2, key3;
char buf[100] = {0};
char buf1[] = "This is a sample";
char buf2[] = "to show sprintf working";
char ipaddr_str[] = "=192.168.100.220";
char a_buf[256] = { 0 }, b_buf[256] = {0};
char bufA[] = "I am bufa";
char bufB[] = "I am bufb";
int ipaddr[4] = {0}, len = 0;
FILE *fp = NULL;
//演示printf 和 scanf功能
printf_s("please input key1, key2,key3, press \"enter\" to complete each value\r\n");
scanf_s("%d %d %d", &key1, &key2, &key3);
printf_s("key1 = %d, key2 = %d, key3 = %d...\r\n", key1, key2, key3);
//演示sprintf功能==>合并多个buffer
sprintf_s(buf, "%s ====> %s", buf1, buf2); //合并buf1和buf2
printf_s("%s \r\n", buf);
//演示sscanf功能
sscanf_s(ipaddr_str, "=%d.%d.%d.%d", &ipaddr[0], &ipaddr[1], &ipaddr[2], &ipaddr[3]); //按照设定格式,将字符串拆分
printf_s("The ip address is: %d.%d.%d.%d\r\n", ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3]);
//演示fprintf 和 fscanf功能
printf_s("please input a string(length < 256): \r\n");
scanf_s("%s", a_buf, sizeof(a_buf));
if (fopen_s(&fp,"./tmp", "w+") < 0)
{
return -1;
}
//根据参数format字符串来转换并格式化数据,然后将结果输出到参数stream指定的文件中,直到出现字符串结束('\0')为止。
fprintf_s(fp, "%s", a_buf); //将a_buf中的字符串转换并输出到fp文件流指定的文件中。
fseek(fp, 0,SEEK_SET);
//会自参数stream的文件流中读取字符串,再根据参数format字符串来转换并格式化数据。
fscanf_s(fp, "%s", b_buf, sizeof(b_buf)); //从fp文件流中读取字符串到b_buf中
printf_s("The final string is : %s \r\n", b_buf);
if (strstr(bufA, "bufa")) //判断字符串是否包含子字符串"bufa"
{
printf_s("This is bufa! ");
}
if (!strstr(bufA, "bufb"))
{
printf_s("This is not bufb! \r\n");
}
if (strlen(bufA) == strlen(bufB))
{
len = strlen(bufA); //获取字符串长度
printf_s("The length is the same. It's %d\r\n", len);
}
else
{
printf_s("The length is different.\r\n");
}
printf_s("The content of bufA is:%s\r\n", bufA);
printf_s("The content of bufB is:%s\r\n", bufB);
return 0;
}
运行结果: