Computer Science Canada Checking if user's input is an integer, real, or string |
Author: | rockmanrock [ Thu May 21, 2020 8:35 pm ] |
Post subject: | Checking if user's input is an integer, real, or string |
Hello there, I am trying to make a calculator of sorts, and when the user enters a string it will crash and tell me there is an "invalid real number input". How can I check if the user has entered a string so I can implement a fail-safe and allow them to try again? Thanks for any help. |
Author: | scholarlytutor [ Thu May 28, 2020 10:55 pm ] |
Post subject: | Re: Checking if user's input is an integer, real, or string |
There are different ways to do this. If you didn't care about the program crashing, you could just use a real variable to get the user's input. If the user typed a string, the program would terminate. I'm assuming however that you do NOT want the program to crash - you want the user to have another try. Thus, you're using a string variable to capture the input, correct? A string can accept both letters and numbers, but you can't do calculations with them since they are strings. While there are different ways to solve your issue, I'm going to recommend these functions: strreal and strrealok. The function strrealok needs to be used to check if the user actually typed a number (whether a whole number or decimal). If they did, strrealok gives you the value 'true'. If however the user did not type a number, strrealok will give you false. So you can do the following. We will trap the user into a loop until they type a number: var userInput : string var checkUserInput : boolean loop get userInput checkUserInput := strrealok(userInput) if not(checkUserInput) then put "That is not a number! Please try again" else exit end if end loop Finally, once the user has entered a number, you should use strreal to convert it from a string to a real number. That way you'll be able to do calculations. Hope this helped! |
Author: | rockmanrock [ Thu Jun 04, 2020 8:21 pm ] |
Post subject: | Re: Checking if user's input is an integer, real, or string |
scholarlytutor @ Thu May 28, 2020 10:55 pm wrote: Hope this helped! It certainly did help, thank you very much. |