1. 程式人生 > >sprintf 字串格式化

sprintf 字串格式化

It may be old-fashioned, but I still find printf (and sprintf and _vsnprintf) incredibly useful, both for printing debug output and for generating formatted strings.

Here are a few lesser-known formats that I use again and again. See MSDN for thefull reference.

A quick review of some of the basics

%04x - 4-digit hex number with leading zeroes

%x prints an int in hexadecimal.

%4x prints a hex int, right-justified to 4 places. If it's less than 4 digits, it's preceded by spaces. If it's more than 4 digits, you get the full number.

%04x prints a hex int, right-justified to 4 places. If it's less than 4 digits, it's preceded by zeroes. If it's more than 4 digits, you get the full number, but no leading zeroes.

Similarly, %d prints a signed int in decimal, and %u prints an unsigned int in decimal.

Not so similarly, %c prints a character and %s prints a string. For wide (Unicode) strings, prefixing with l (ell, or w): %lc and %ls.

Note: For the Unicode variants, such as wprintf and friends, %c and %s print wide strings. To force a narrow string, no matter which variant, use the %h size prefix, and to force a wide string, use the %l size prefix; e.g., %hs and %lc.

%p - pointer

The wrong way to print a pointer is to use %x. The right way is to use %p. It's portable to Win64, as well as to all other operating systems.

Everyone should know this one, but many don't.

%I64d, %I64u, %I64x - 64-bit integers

To print 64-bit numbers (__int64), use the I64 size prefix.

%Iu, %Id, %Ix - ULONG_PTR

ULONG_PTR, LONG_PTR, and DWORD_PTR are numeric types that are as wide as a pointer. In other words, they map to ULONG, LONG, and DWORD respectively on Win32, and ULONGLONG, LONGLONG, and ULONGLONG on Win64.

The I size prefix (capital-i, not lowercase-L) is what you need to print *LONG_PTR on Win32 and Win64.

%*d - runtime width specifier

If you want to calculate the width of a field at runtime, you can use %*. This says the next argument is the width, followed by whatever type you want to print.

For example, the following can be used to print a tree:

void Tree::Print(Node* pNode, int level)
{
if (NULL != pNode)
{
Print(pNode->Left, level+1);
printf("%*d%s"n", 2 * level, pNode->Key);
Print(pNode->Right, level+1);
}
}

%.*s - print a substring

With a variable precision, you can print a substring, or print a non-NUL-terminated string, if you know its length. printf("%.*s"n", sublen, str) prints the first sublen characters of str.

[2005/7/19: fixed a typo in previous sentence (%.s -> %.*s). A little elaboration on the syntax: . in a printf format specification is followed by theprecision. For strings, the precision specificies how many characters will be printed. A precision of * indicates that the precision is the next argument on the stack. If the precision is zero, then nothing is printed. If a string has a precision specification, its length is ignored.]

%.0d - print nothing for zero

I've occasionally found it useful to suppress output when a number is zero, and %.0d is the way to do it. (If you attempt to print a non-zero number with this zero-precision specifier, it will be printed.) Similarly, %.0s swallows a string.

%#x - print a leading 0x

If you want printf to automatically generate 0x before hex numbers, use %#x instead of %x. .

Security

Never use an inputted string as the format argument: printf(str). Instead, use printf("%s", str). The former is a stack smasher waiting to happen.

%n is dangerous and disabled by default in VS2005.

Don't use sprintf. Use the counted version, _snprintf or _vsnprintf instead. Better still, use theStrSafe.h functions, StringCchPrintf and StringCchVPrintf, to guarantee that your strings are NUL-terminated.

Note:

printf各項的意義介紹如下:
1) 型別:型別字元用以表示輸出資料的型別,其格式符和意義如下表所示:
格式字元 意義
d 以十進位制形式輸出帶符號整數(正數不輸出符號)
o 以八進位制形式輸出無符號整數(不輸出字首0)
x,X 以十六進位制形式輸出無符號整數(不輸出字首Ox)
u 以十進位制形式輸出無符號整數
f 以小數形式輸出單、雙精度實數
e,E 以指數形式輸出單、雙精度實數
g,G 以%f或%e中較短的輸出寬度輸出單、雙精度實數
c 輸出單個字元
s 輸出字串
2) 標誌:標誌字元為-、+、#、空格四種,其意義下表所示:
標 志 意義
- 結果左對齊,右邊填空格
+ 輸出符號(正號或負號)
空格 輸出值為正時冠以空格,為負時冠以負號
# 對c,s,d,u類無影響;對o類,在輸出時加字首o;對x類,在輸出時加字首0x;對e,g,f 類

當結果有小數時才給出小數點
3) 輸出最小寬度: 用十進位制整數來表示輸出的最少位數。若實際位數多於定義的寬度,則按實際位數輸出,若實際位數少於定義的寬度則補以空格或0。
4) 精度: 精度格式符以“.”開頭,後跟十進位制整數。本項的意義是:如果輸出數字,則表示小數的位數;如果輸出的是字元,則表示輸出字元的個數;若實際位數大於所定義的精度數,則截去超過的部分。
5) 長度:長度格式符為h,l兩種,h表示按短整型量輸出,l表示按長整型量輸出。

最後,總是有人碰到了問題如下:

將DWORD變數格式化到CString中來,但結果顯示不正確。
DWORD a=399811571;
CString str;
str.Format("%d",a);
Format裡面用"%ld"也不行 ,其結果字串為 到符號的數字字串。

正確的格式為:str.Format("%u",a); 之前碰到過不知道怎麼辦,後來想起來了。^_^

相關推薦

sprintf 字串格式化

It may be old-fashioned, but I still find printf (and sprintf and _vsnprintf) incredibly useful, both for printing debug output and for generating formatt

C++字串格式化 sprintf、printf

sprintf 的格式控制串中既然可以插入各種東西,並最終把它們"連成一串",自然也就能夠連線字串,從而在許多場合可以替代strcat,但sprintf 能夠一次連線多個字串(自然也可以同時在它們中間插入別的內容,總之非常靈活)。比如: char* who = "I"; char* whom = "CSDN"

sprintf sprintf_s ... 格式化字串 統一之路?

不知道大家在格式化字串的時候是怎麼做的?是不是也通常使用 sprintf(buffer,"%s%d%s",.....) 這個函式嗎? 而在VS2005下,會提示這個函式已經過期了,並建議用更加安全的 sprintf_s(buffer,size,"%s",.....); 來代替

字串格式化 sprintf

sprintf 是個變參函式,定義如下: int sprintf( char *buffer, const char *format [, argument] … );除了前兩個引數型別固定外,後面可以接任意多個引數。而它的精華,顯然就在第二個引數:格式化字串

python字串格式化% 操作符 {}操作符 python字串格式化 %操作符 {}操作符---總結 Python字串格式化 (%佔位操作符)

python字串格式化 %操作符 {}操作符---總結 Python字串格式化 (%佔位操作符) 在許多程式語言中都包含有格式化字串的功能,比如C和Fortran語言中的格式化輸入輸出。Python中內建有對字串進行格式化的操作 %。 模板 格式化字串時,Python使用一個字串作為模板。模

Newtonsoft.Json序列化字串-格式化和時間格式問題

最近C#中需要將實體進行json序列化,使用了Newtonsoft.Json         public static void TestJson()        {        &

python的2種字串格式化輸出

 字串格式化程式碼(typecode)     法一: %格式使用下面的格式 %[(name)] [flags] [width][.precision] typecode (name)輸出字典的value使用,這裡的name是字典的key(實際指定時,必須有外面的

String.format() ------ java字串格式化

一、簡單介紹  1、作用:String類的format()方法用於建立格式化的字串以及拼接多個字串物件。 2、String.format()的兩種使用方式:   ①方式一:             &

第4章:介紹python物件型別/4.1 python的核心資料型別/4.2 字串/4.2.4 字串格式化字串編輯HTML或者XML語法、使用正則表示式

字串格式化 %s 方式格式化: >>> "%s,abc,%s" %('123','456') '123,abc,456' {數字}方式格式化: >>> "{0},abc,{1}".format('123','456') '123,a

Python3 | 字串格式化 format 和 % 的使用

Python3 字串格式化 字串的格式化方法分為兩種,分別為佔位符(%)和format方式。佔位符方式在Python2.x中用的比較廣泛,隨著Python3.x的使用越來越廣,format方式使用的更加廣泛。 一 佔位符(%)   %d 例項(Python3.0+):

python字串格式化%和{}操作符

python字串格式化 %操作符 {}操作符---總結 Python字串格式化 (%佔位操作符) 在許多程式語言中都包含有格式化字串的功能,比如C和Fortran語言中的格式化輸入輸出。Python中內建有對字串進行格式化的操作 %。 模板 格式化字串時,Python使用一個字串作為

[基礎]-python字串格式化輸出

如果將那個定義說的通俗一些,字串格式化化,就是要先制定一個模板,在這個模板中某個或者某幾個地方留出空位來,然後在那些空位填上字串。那麼,那些空位,需要用一個符號來表示,這個符號通常被叫做佔位符(僅僅是佔據著那個位置,並不是輸出的內容)。   >>> "I li

python之路-Day05字串格式化

format格式化方法 根據索引去傳一個值 tpl = "my name is {1},age{1}".format("ZhouJieLun",18,"milktea") print(tpl) 根據鍵值對的方法去傳一個值 如果需要傳字典那麼在括號的name前面加兩個**就可

Python字串格式化快速入門例項(自3.7官方文件)

Python字串格式化例子 Shawn python3.7 文件: https://docs.python.org/3/library/string.html#formatstrings 完整功能介紹見官方文件. 本文可用於快速查詢Python字串格

js字串格式化方法format

/** * 設定字串format函式 * 例子: '{0}{1}.format(5,6)' */ setStringFormat() { String.prototype['format'] = function () { const e = arguments; retu

Python類與物件技巧(1):字串格式化、封裝屬性名、可管理的屬性、呼叫父類方法

1. 自定義字串的格式化 _formats = { 'ymd' : '{d.year}-{d.month}-{d.day}', 'mdy' : '{d.month}/{d.day}/{d.year}', 'dmy' : '{d.day}/{d.month}/{d.ye

關於字串格式化

format 相對於比%s 使用更簡潔明瞭,少些囉嗦info =(f"------------ info if {name} --------\n"f"name = {name}\n"f"age = {age}\n"f"hometown =

Python3-字串格式化

字串是 Python 中最常用的資料型別。我們可以使用引號('或")來建立字串。 var1 = 'Hello World!' var2 = "Runoob"   今天記錄字串格式化 格式化字串時,Python使用一個字串作為模板。模板中有格式符,這些格式符為真實值預留位置,並說明真實數值應該

(轉載)JAVA字串格式化-String.format()的使用

文章原地址 https://www.cnblogs.com/Dhouse/p/7776780.html 常規型別的格式化 String類的format()方法用於建立格式化的字串以及連線多個字串物件。熟悉C語言的同學應該記得C語言的sprintf()方法,兩者有類似之處

python字串格式化之format

用法:   它通過{}和:來代替傳統%方式 1、使用位置引數 要點:從以下例子可以看出位置引數不受順序約束,且可以為{},只要format裡有相對應的引數值即可,引數索引從0開,傳入位置引數列表可用*列表 >>> li = ['hoho',18] >>> 'm