1
只需用簡單的計算器進行練習。我嘗試着跑到前面,並將其封裝在do-while循環中。然後我有一個奇怪的行爲 - catchin每個新循環的空字符串。可以看到,在case ""
的代碼部分。從stdio讀取輸入時不需要的空字符串
所以這個問題 - 正在發生什麼,以及如何處理它?
可以看到我的謙卑嘗試註釋行修復它在代碼:
import std.stdio;
import std.string;
void main() {
writefln("--- Welcome to calculatro %s ---", " ");
int exit = 0;
do {
string op;
double first;
double second;
writeln("enter operator :");
op = chomp(readln());
writeln("operator :",op,":");
//readf(" %s/n", &op);
switch (op) {
case "add", "+":
writeln("enter two values :");
//readf(" %s %s", &first, &second);
readf(" %s", &first);
readf(" %s", &second);
writefln("%s+%s=%s", first, second, first+second);
//writeln(first+second);
break;
case "minus", "-", "substract":
writeln("enter two values :");
readf(" %s %s", &first, &second);
writefln("%s+%s=%s", first, second, first-second);
break;
case "exit":
exit = 1;
break;
case "":
writeln("empty op");
break;
default:
writefln("i dont know op!"~op);
//writefln("%(%s%)", op);
//writefln("%s", op);
//throw new Exception(format("Unknown operation: %s", op));
break;
}
} while (exit == 0);
writeln("good bye!");
}
非常感謝您的詳細解釋! – Rijk