用简单的计算器锻炼身体。我试图跑到前面,把它包裹在do-while循环中。然后我有一个奇怪的行为 - 在每个新循环上捕获空字符串。可以在case ""
代码部分看到。
所以问题 - 发生了什么以及如何处理它?
我可以看到我在代码中的注释行上修改它的拙劣尝试:
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!");
}
答案 0 :(得分:7)
考虑一下'calculatro':
--- Welcome to calculatro ---
enter operator :
+
operator :+:
enter two values :
4 5
4+5=9
enter operator :
operator ::
empty op
enter operator :
readln
来使用所有stdio readf
消费'4 5',在stdio上留下'\ n' readln
从stdio readln
能够读取整行,因此不会从输入提示用户chomp
删除'\ n',留下空字符串这里的快速解决方法是在您的操作数消耗尾随换行符后调用readln
。例如:
case "add", "+":
writeln("enter two values :");
//readf(" %s %s", &first, &second);
readf(" %s", &first);
readf(" %s", &second);
readln(); // <----- read trailing newline
writefln("%s+%s=%s", first, second, first+second);
//writeln(first+second);
break;