2

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!

1 Answer 1

4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.