2013-07-24 22 views
0

用戶輸入我有用戶輸入一個簡單的提示,如下所示:如何重新提示在TCL

Is this correct? (Y/N): 

此提示應該只需要無論是YN,應該重新提示用戶如果有其他輸入已經輸入。

有人可以告訴我關於如何做到這一點的代碼片段?我對Tcl仍然很陌生。

+0

'而{[提出-nonewline {這是正確的(Y/N)};設定輸入[得到的stdin]] NI {YN}} {}' –

+0

嗯,四(井,5個)的方式來這樣做,所有這些都略有不同。如果你想得到更好的答案,限制更多一點... –

回答

1

這是不是很難做的很好。關鍵是在打印提示後檢查flush,檢查文件結束(使用否定結果並致電eof),並在發生這種情況時採取措施停止,並使用-strictstring is調用。

proc promptForBoolean {prompt} { 
    while 1 { 
     puts -nonewline "${prompt}? (Yes/No) " 
     flush stdout; # <<<<<<<< IMPORTANT! 
     if {[gets stdin line] < 0 && [eof stdin]} { 
      return -code error "end of file detected" 
     } elseif {[string is true -strict [string tolower $line]]} { 
      return 1 
     } elseif {[string is false -strict [string tolower $line]]} { 
      return 0 
     } 
     puts "Please respond with yes or no" 
    } 
} 

set correct [promptForBoolean "Is this correct"] 
puts "things are [expr {$correct ? {good} : {bad}}]" 
0

您可以通過以下代碼片段:從stdin(標準輸入)獲取數據,直到找到有效的東西。

puts "Is this correct? (Y/N)" 

set data "" 
set valid 0 
while {!$valid} { 
    gets stdin data 
    set valid [expr {($data == Y) || ($data == N)}] 
    if {!$valid} { 
     puts "Choose either Y or N" 
    } 
} 

if {$data == Y} { 
    puts "YES!" 
} elseif {$data == N} { 
    puts "NO!" 
} 
+0

爲什麼容易,如果有一個複雜的方式來做到這一點? –

0

這就是我該怎麼做的。它不區分大小寫,接受y,yes,nno

proc yesNoPrompt {question} { 
    while {1} { 
    puts -nonewline stderr "$question (Y/N): " 
    if {[gets stdin line] < 0} { 
     return -1 
    } 
    switch -nocase -- $line { 
     n - no { 
     return 0 
     } 
     y - yes { 
     return 1 
     } 
    } 
    } 
} 

yesNoPrompt "Is this correct?" 
0

那麼,這將接受Y,是的,真正的,1,N,沒有,假的... ...

proc isCorrect {} { 
    set input {} 
    while {![string is boolean -strict $input]} { 
     puts -nonewline {Is this correct (Y/N)} 
     flush stdout 
     set input [gets stdin] 
    } 
    return [string is true -strict $input] 
} 
if {[isCorrect]} { 
    puts "Correct" 
} else { 
    puts "not correct" 
} 
+1

有關布爾值的官方列表記錄在案(http://tcl.tk/man/tcl8.5/TclLib/GetInt.htm#M5) –