你们是如何处理控制台输入验证的?在C++中,case/switch是我的goto...
我正在尝试一个递归函数,但被锁定在较低的级别。另外,这可能有些过头了。我确实使用“异或”来管理一个while循环,但这并不是真正可伸缩的。
function prob6()
println("Pick a number; any number:")
x = readline(stdin)
y = parse(Int64, x)
z = 0
println("Select 1 or 2")
p1 = readline(stdin)
p2 = parse(Int64, p1)
select = p2
while xor((p2 == 1), (p2 == 2)) == false
println("Select 1 or 2")
p1 = readline(stdin)
p2 = parse(Int64, p1)
select = p2
end
if select == 1
for i in 1:y
print("$i ")
z = z + i
end
else
z = 1
for i in 1:y
print("$i ")
z = z * i
end
end
println(z)
end有其他选择吗?
发布于 2019-05-22 06:25:33
有很多种方法。我通常创建一个验证循环来检查输入项的类型,并且将使用tryparse而不是parse,因为如果输入格式错误,它不会抛出错误:
function queryprompt(query, typ)
while true
print(query, ": ")
choice = uppercase(strip(readline(stdin)))
if (ret = tryparse(typ, choice)) != nothing
return ret
end
println()
end
end
n = queryprompt("Integer please", Int64)
println(n)
x = queryprompt("Float please", Float64)
println(x)https://stackoverflow.com/questions/56245933
复制相似问题