sprintf()与sscanf()

本文详细介绍了C语言中的格式化输入输出函数,包括sprintf()、sscanf()、vsprintf()等函数的功能与使用方法,并提供了实例代码进行说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、sprintf() (swprintf() 、_stprintf())作用为将格式化的数据输出到一个字符串buffer中,sprintf_s()为其安全版本,

int sprintf(char *buffer, const char *format, [argument] ...);
	int dSrc1 = 1;
	int dSrc2 = 2;
	TCHAR strSrc[] = _T("hello");

	TCHAR AryDest[100] = {0};

	_stprintf(AryDest, L"%4d,%4d,%s", dSrc1,dSrc2,strSrc);//AryDest:"   1,   2,hello"

        fprintf(FILE* Stream, const char* Format, ...)可以将格式化的数据输入到文件中。


2、sscanf() (swscanf() 、_stscanf())作用为从一个字符串buffer中读取与指定格式相符的数据,sscanf_s()为其安全版本, 

int sscanf(const char *buffer, const char *format, [argument ] ...);
	TCHAR strSrc[] = _T("   1,   2,hello");

	int dDest1;
	int dDest2;
	TCHAR strDest[100] = {0};
	
	_stscanf(strSrc, _T("%4d,%4d,%s"), &dDest1,&dDest2,strDest);//dDest1:1, dDest2:2, strDest:"hello"
        fscanf(FILE* Stream, const char* Format, ... )可以从文件中读取与指定格式相符的数据。

3、vsprintf()与vfprintf()功能与sprintf()和fprintf()相同,只不过如果vsprintf()或vfprintf()的实参来自于调用函数的参数,那么我们就使用vsprintf()或vfprintf(),eg:

       

void Trace(FILE* pFile, const char* format, ...)
{
	va_list args;
	va_start(args, format);
	vfprintf(pFile, format, args);
	va_end(args);
	fflush(pFile);
}

Trace(pFile, "hello: %d", nNum);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值