Computer Science Canada How do you make sure the user enters a number only?? |
Author: | confuzzius [ Fri Feb 13, 2004 6:02 pm ] |
Post subject: | How do you make sure the user enters a number only?? |
well, pretty much right there in the subject line... i want to do this program that manupulates an entered number. but, when the user enters a string, the program exits because of error. is there a way i can stop the auto-exiting? and btw, i need to be able to multiply the entered number with other numbers. |
Author: | santabruzer [ Fri Feb 13, 2004 6:16 pm ] | ||
Post subject: | |||
enjoy
|
Author: | TheXploder [ Fri Feb 13, 2004 6:18 pm ] | ||
Post subject: | |||
ohh, well I used char instead of string:
|
Author: | Delos [ Fri Feb 13, 2004 6:21 pm ] | ||
Post subject: | |||
This problem is known as error trapping. There are a lot of ways of doing this. First understand this: A variable that is Inputted by the User can only be stored if its type matches that of which it was declared as. i.e. Declare an int, you can only enter ints, or it crashes. This, I'm sure you've figured out. Now, here's something interesting. Strings, as you may have noticed, also include numbers "0"-"9". So, theoretically, one could declare a string variable, input numbers into it, and all would be fine. But you need to multiply the numbers. Answer? strint STRing-to-INT command. This takes a string value, and attempts to assign it to an integer. Of course, if the string is not a pure integer, it will not work (there are ways around that). Try this:
The idea behind this code is that you can see how it will crash either way (if you enter string into the strint command, or string into a normal int get). So what to do about it? I hope you know about the index function. This is used to find patterns of strings within a string. So, to fix the above code, you need to make up a little algorithm that will look at the string that is gotten by the "get temp" line, and check to make sure that it is all int. If it is, then you can turn it into an int using strint. As I said, there are much easier ways of doing this, but it's always more fun to try and figure out a way by yourself. Any more questions? Post again! Edit: In the time it took me to type this, 2 ppl had already posted! Hahaha. That's funny...ah well. |
Author: | confuzzius [ Sat Feb 14, 2004 11:34 pm ] |
Post subject: | Gratitude |
thanks everyone for your help! i found that santabruzer's post was the easiest for me to understand though.... 'cause it's much shorter hehehe... but thanks anyway! |
Author: | Andy [ Sun Feb 15, 2004 9:33 pm ] |
Post subject: | |
its cuz delos doesnt read |