在 c++ 中,可以使用 printf 函數(shù)輸出格式化數(shù)據(jù),但推薦使用 iostream 庫(kù)中的 cout 對(duì)象。語(yǔ)法為 printf(const char *format, …),其中 format 指定格式,… 是可變參數(shù)列表包含要輸出數(shù)據(jù)。格式說(shuō)明符(如 %d、%f、%s)控制輸出格式。
printf 在 C++ 中的使用
printf 是一個(gè) C 語(yǔ)言庫(kù)中的函數(shù),用于將格式化后的數(shù)據(jù)輸出到標(biāo)準(zhǔn)輸出(通常是控制臺(tái))。在 C++ 中,也可以使用 printf 函數(shù),但更推薦使用 C++ 的 iostream 庫(kù)提供的 iostream 對(duì)象,例如 cout。
語(yǔ)法
printf(const char *format, ...);
其中:
format
:一個(gè)格式化字符串,指定輸出數(shù)據(jù)的格式。
...
:可變參數(shù)列表,其中包含要輸出的數(shù)據(jù)。
格式說(shuō)明符
格式字符串中可以使用格式說(shuō)明符來(lái)控制輸出數(shù)據(jù)的格式。一些常用的格式說(shuō)明符包括:
%d
:有符號(hào)十進(jìn)制整數(shù)
%u
:無(wú)符號(hào)十進(jìn)制整數(shù)
%f
:浮點(diǎn)數(shù)
%s
:字符串
%c
:字符
使用示例
<code class="cpp">#include <cstdio> int main() { int age = 25; float salary = 10000.50; char name[] = "John Doe"; printf("年齡:%d\n", age); printf("工資:%.2f\n", salary); printf("姓名:%s\n", name); return 0; }</cstdio></code>
登錄后復(fù)制
輸出:
<code>年齡:25 工資:10000.50 姓名:John Doe</code>
登錄后復(fù)制
注意:
printf 函數(shù)不檢查格式化字符串中的錯(cuò)誤,因此使用時(shí)要小心。
iostream 庫(kù)更安全且更易于使用,因此推薦使用 cout 和 cerr 對(duì)象進(jìn)行輸出。