[ Skill ] print println printf fprintf sprintf lsprintf


https://www.cnblogs.com/yeungchie/

幾種 print 函數的差異

print

  • 接收任意的數據類型,並打印到 CIW
print( 12345 )        ; 12345
print( "YEUNGCHIE" )  ; "YEUNGCHIE"
print( winId )        ; window:1
print( cvId )         ; db:0x21e4c01a
  • 第二參數可選指定 IO 句柄
print( "String" port )
  • 返回值恆為 nil

println

  • print 區別在於 println 打印一個數據后會自動換行

舉個例子,同時運行 3 個 print

print( 1 ) print( 2 ) print( 3 )
; 123

同時運行 3 個 println

println( 1 ) println( 2 ) println( 3 )
; 1
; 2
; 3

printf

  • 格式化輸出字符串
  • 第一個參數定義輸出字符串格式 format,例如下面能夠識別其中的 轉義符(\) 和 字符串占位符(%s)
  • 從第二個參數開始會依次替換 format 中定義的 占位符
who = "YEUNGCHIE"
printf( "My name is %s and weight is %d kg\n" who 999 )
; My name is YEUNGCHIE and weight is 999 kg
  • 輸出成功,返回 t,輸出不成功都是報 error。

更詳細的使用方法可以看以前的這篇隨筆 [ Skill ] 中的通用輸出格式規范

fprintf

  • printf 的區別是,用來輸出到 IO 句柄(可以用來輸出到文件)
file = outfile( "~/text.txt" )
fprintf( file "My name is %s and weight is %d kg\n" "YEUNGCHIE" 999 )
close(file)
  • 將會生成一個文件 ~/text.txt
> cat ~/text.txt
My name is YEUNGCHIE and weight is 999 kg
  • 成功輸出到文件即返回 t

sprintf

  • fprintf 的區別是,不直接打印結果,而是將結果作為函數的輸出,你可以賦值給 變量
sprintf( variable "My name is %s and weight is %d kg\n" "YEUNGCHIE" 999 )
variable = sprintf( nil "My name is %s and weight is %d kg\n" "YEUNGCHIE" 999 )
; "My name is YEUNGCHIE and weight is 999 kg"

上面兩句的效果是一樣的,variable 將會被賦值為格式化后的字符串。

  • 成功格式化即返回字符串內容

lsprintf

  • sprintf 的區別是,第一個參數不用於指定被賦值的變量。
string = lsprintf( "My name is %s and weight is %d kg\n" "YEUNGCHIE" 999 )
  • 成功格式化即返回字符串內容
  • 當輸出的參數數量不確定的時候這個函數非常好用,舉個例子:
format = "My name is %s and weight is %d kg\n"
args   = list( "YEUNGCHIE" 999 )
string = apply( 'lsprintf format args )
; "My name is YEUNGCHIE and weight is 999 kg"
  • 當然 sprintf 也是可以的,只不過需要多加一個 nil
string = apply( 'sprintf nil format args )
; "My name is YEUNGCHIE and weight is 999 kg"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM