C/C++ printf 列印 size_t 的方法

本篇將介紹在 C/C++ 程式裡如何 printf 印出 size_t 這個變數類型,最常用到就是 vector::size(),或者是其它 STL 容器的 size() 也是如此。

這邊舉例用 printf 印出 vector 的 size,如下例程式,

cpp-printf-size_t.cpp
1
2
3
4
5
6
7
8
9
// g++ cpp-printf-size_t.cpp -o a.out -std=c++11
#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> v = {1, 2, 3, 4, 5};
printf("size=%d", v.size());
}

編譯後會得到一個編譯警告,如下所示,

1
2
cpp-printf-size_t.cpp:8:31: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘std::vector<int>::size_type {aka long unsigned int}’ [-Wformat=]
printf("size=%d", v.size());

透過查詢後得知 size 回傳型態是 size_type,size_type 又定義成 size_t,

size_t 在 printf 要用 %zu,順便補充一下,ssize_t 在 printf 要用 %zd
改成這樣後再編譯一次就沒有出現 compile warning 了,

cpp-printf-size_t2.cpp
1
2
3
4
5
6
7
8
9
// g++ cpp-printf-size_t2.cpp -o a.out -std=c++11
#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> v = {1, 2, 3, 4, 5};
printf("size=%zu", v.size());
}

參考
c - How can one print a size_t variable portably using the printf family? - Stack Overflow
https://stackoverflow.com/questions/2524611/how-can-one-print-a-size-t-variable-portably-using-the-printf-family
What is the correct way to use printf to print a size_t in C/C++?
https://www.tutorialspoint.com/what-is-the-correct-way-to-use-printf-to-print-a-size-t-in-c-cplusplus

其它相關文章推薦
C/C++ 新手入門教學懶人包
32/64bit 作業系統 printf 列印 int64_t / uint64_t 的方法