【WIN】【C/C++】格式化输入字符串——sprintf 和 StringCchPrintf

678 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

sprintf

函数原型

int sprintf( char *buffer, const char *format [, argument,...] );
  • buffer:指向一个字符数组的指针,该数组存储了C字符串。
  • format:字符串,包含了要被写入到字符串buffer的文本。可以包含嵌入的format标签,并按需求进行格式化。

demo

#include <stdio.h>
#include <math.h>

int main()
{
   char str[80];

   sprintf(str, "Pi 的值 = %f", M_PI);
   puts(str);
   
   return(0);
}

使用sprintf 的常见问题

sprintf 是个变参函数,使用时经常出问题,而且只要出问题通常就是能导致程序崩溃的内存访问错误,但好在由sprintf 误用导致的问题虽然严重,但是只要细心就可以避免这些问题的发生。

  1. 缓冲区溢出

第一个参数的长度太短了,没的说,给个大点的地方吧。当然也可能是后面的参数的问题,建议变参对应一定要细心,而打印字符串时,尽量使用%.ns的形式指定最大字符数。

  1. 忘记了第一个参数

低级得不能再低级问题,用printf 用得太惯了。

  1. 变参对应出问题

通常是忘记了提供对应某个格式符的变参,导致以后的参数统统错位,检查检查吧。尤其是对应*的那些参数,都提供了吗?不要把一个整数对应一个%s

StringCchPrintf

函数原型

STRSAFEAPI StringCchPrintfA(
  [out] STRSAFE_LPSTR  pszDest,
  [in]  size_t         cchDest,
  [in]  STRSAFE_LPCSTR pszFormat,
        ...            
);
  • pszDest:The destination buffer, which receives the formatted, null-terminated string created from pszFormat and its arguments.
  • cchDest:The size of the destination buffer, in characters. This value must be sufficiently large to accommodate the final formatted string plus 1 to account for the terminating null character. The maximum number of characters allowed is STRSAFE_MAX_CCH.

STRSAFE_MAX_CCH:字符串最大长度: 2,147,483,6472,147,483,647

demo

TCHAR pszDest[30];
size_t cchDest = 30;
LPCTSTR pszFormat = TEXT("%s%d+%d=%d.");
TCHAR* pszTxt = TEXT("Theansweris");
HRESULT hr = StringCchPrintf(pszDest, cchDest, pszFormat, pszTxt, 1, 2, 3);
//TheresultantstringatpszDestis"Theansweris1+2=3."