0

我是 TCL 的新手,我正试图围绕它使用的 ""、{} 和 [] 的所有用法展开我的大脑。我习惯用其他语言做的事情是在使用之前定义我的变量,在应用程序的开头。以下代码有效:

puts "Please enter an integer of choice to be added: "
flush stdout
gets stdin intAnswer

puts "Please enter a second integer of choice to be added: "
flush stdout
gets stdin intAnswerTwo

puts "Please enter a third integer of choice to be added: "
flush stdout
gets stdin intAnswerThree

puts "The total of the three integers is: [expr $intAnswer + $intAnswerTwo + $intAnswerThree]"

我想要做的是在使用之前定义变量。像这样:

set intAnswer 0
set intAnswerTwo 0
set intAnswerThree 0
set intTotal 0

此代码放在开头,不适用于其余代码。我错过了什么?

4

1 回答 1

1

该代码对我来说看起来绝对没问题,但[expr {$intAnswer + $intAnswerTwo + $intAnswerThree}]会更好(因为它阻止了对变量内容的潜在重新解释,这既是安全问题又是性能问题)。

但是,如果您真的想从用户那里获得整数,则需要验证他们的输入。这很容易通过编写一个程序来完成这项工作,以便您可以重用它(即,您重构代码以获得一个值,以便您可以使用更复杂的版本并一次正确地完成它):

proc getIntFromUser {message} {
    # Loop forever (until we [exit] or [return $response])
    while true {
        puts $message
        flush stdout
        set response [gets stdin]
        # Important to check for EOF...
        if {[eof stdin]} {
            exit
        }
        # The validator (-strict is needed for ugly historical reasons)
        if {[string is integer -strict $response]} {
            return $response
        }
        # Not an integer, so moan about it
        puts "\"$response\" is not an integer!"
    }
}

现在你有了这个过程,你的其余代码可以变成:

set intAnswer      [getIntFromUser "Please enter an integer of choice to be added: "]
set intAnswerTwo   [getIntFromUser "Please enter a second integer of choice to be added: "]
set intAnswerThree [getIntFromUser "Please enter a third integer of choice to be added: "]

puts "The total of the three integers is: [expr {$intAnswer + $intAnswerTwo + $intAnswerThree}]"

编写好的 Tcl 代码(或几乎任何其他语言的好代码)的艺术是知道重构的优点是什么。一个好的起点是“如果你做两次或多次,做一次并分享”。如果你能给程序起一个好听的名字和清晰的界面,那是双倍的好,清楚地表明你做对了。事实上,你也可以去:

set total [expr {
    [getIntFromUser "Please enter an integer of choice to be added: "] +
    [getIntFromUser "Please enter a second integer of choice to be added: "] +
    [getIntFromUser "Please enter a third integer of choice to be added: "]
}]

puts "The total of the three integers is: $total"

用户观察到的结果将是相同的。

于 2013-03-02T13:07:32.240 回答