• [ 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 也不是做不到,只不过会比较麻烦。
    string = apply(
      lambda(( a \@rest b )
        apply( 'sprintf nil a b )
      )
      format
      args
    )
    ; "My name is YEUNGCHIE and weight is 999 kg"
    
  • 相关阅读:
    【Luogu1501】Tree(Link-Cut Tree)
    【BZOJ3530】数数(AC自动机,动态规划)
    【BZOJ1212】L语言(AC自动机)
    【BZOJ2037】Sue的小球(动态规划)
    【BZOJ1899】午餐(动态规划)
    【BZOJ1009】GT考试(KMP算法,矩阵快速幂,动态规划)
    【BZOJ1040】骑士(动态规划)
    【BZOJ1969】航线规划(Link-Cut Tree)
    【BZOJ4653】【NOI2016】区间(线段树)
    我也不知道什么是"莫比乌斯反演"和"杜教筛"
  • 原文地址:https://www.cnblogs.com/yeungchie/p/15758985.html
Copyright © 2020-2023  润新知