How to take only Int Input and show error message when another type of input is given

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • shubham1996
    New Member
    • Jul 2015
    • 1

    How to take only Int Input and show error message when another type of input is given

    Hi all
    i am making a program to add two numbers but there is also such condition that only integers to be processed except integer input should be treated as 'Invalid Input'
    please help!
  • HughMann
    New Member
    • Jul 2015
    • 3

    #2
    Answer is in your question: IF it's not int then something, something.
    Just think about how would you define int in programming terms and what do you want to happen if that condition has not been met.
    Good luck!

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      This is harder than it looks.

      If the user enters 123.45, the 123 is an int. In this case you would need to scan for the decimal and then avoid using 123 and 45 as the two ints.

      Since you have no idea what the user will enter most likely you will need to fetch data a character at a time to determine whether it is an int. You would fetch the 1 and see that could be an int. Then fetch the 2 and see that 12 could be an int. Then fetch the 3 and see that 123 could be an int. Then fetch the decimal point and see that it is not part of an int so you ditch 123 and the decimal point. Then fetch characters until you get whitespace which allows ditching the 45. etc.etc.

      Then build in logic that restricts the user to 2 ints.

      Parsing input is so difficult that I tell students to not do it at all and just provide the input the program expects.

      If you do write a parser, be sure to put the code in a library form so you can use it on all of your programs forever.

      This is especially sad since most OS have features that do this if you write using the OS system calls.

      Comment

      Working...