Reputation: 117
I just started working on a very basic calculator program, and it works fine exempt I can't get it to keep the program open after it has completed the calculation. io.read() doesn't seem to work. My code is as follows:
promptmethod = "Would you like to use addition, subtraction, multiplication, or division?"
promptnumber1 = "Enter a number:"
promptnumber2 = "Enter another number:"
anotherprompt = "Would you like to make another calculation?"
print(promptmethod)
usermethod = io.read("*line")
print(promptnumber1)
number1 = io.read("*number")
print(promptnumber2)
number2 = io.read("*number")
if usermethod == "addition" then
answer = number1 + number2
stringanswer = "Your calculation is " .. number1 .. " + " .. number2 .. " = " .. answer
elseif usermethod == "subtraction" then
answer = number1 - number2
stringanswer = "Your calculation is " .. number1 .. " - " .. number2 .. " = " .. answer
elseif usermethod == "multiplication" then
answer = number1 * number2
stringanswer = "Your calculation is " .. number1 .. " × " .. number2 .. " = " .. answer
elseif usermethod == "division" then
answer = number1 / number2
stringanswer = "Your calculation is " .. number1 .. " ÷ " .. number2 .. " = " .. answer
else
error("Invalid operation or values.")
end
print(stringanswer)
io.read()
Does anyone know why this would happen? Thank you!
Upvotes: 2
Views: 2325
Reputation: 28991
A simpler example:
io.read('*number')
io.read()
The problem is that read('*number')
does not consume the newline character after the number. Since that's still sitting on the input stream, so when you call io.read
(which defaults to reading a line), it returns immediately.
To fix that, just call io.read
a second time.
Upvotes: 4