我想知道如何在程序讀取不合適的值後繼續在D中使用stdin。 (例如,字母,當它被期待一個int) 我寫這個測試它:如何在D readf中輸入錯誤類型後讀取輸入?
import std.stdio;
void main()
{
int a;
for(;;){
try{
stdin.readf(" %s", a);
break;
}catch(Exception e){
writeln(e);
writeln("Please enter a number.");
}
}
writeln(a);
}
輸入不正確的值,如「B」之後,程序將打印出消息indefinitly。我還檢查這表明它試圖再次讀取相同的字符異常,所以我做了一個版本是這樣的:
import std.stdio;
void main()
{
int a;
for(;;){
try{
stdin.readf(" %s", a);
break;
}catch(Exception e){
writeln(e);
writeln("Please enter a number.");
char c;
readf("%c", c);
}
}
writeln(a);
}
嘗試讀取時仍然拋出一個異常,但不是C。我也試過使用stdin.clearerr(),它沒有任何作用。有誰知道如何解決這個問題?謝謝。