该代码对我来说看起来绝对没问题,但[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"
用户观察到的结果将是相同的。