I’m experimenting with a Windows batch file to perform a simple operation which requires the user to enter a non-negative integer. I’m using simple batch-file techniques to get user input:
@ECHO OFF SET /P UserInput=Please Enter a Number:
The user can enter any text they want here, so I would like to add some routine to make sure what the user entered was a valid number. That is… they entered at least one character, and every character is a number from 0 to 9. I’d like something I can feed the UserInput into. At the end of the routine would be like an if/then that would run different statements based on whether or not it was actually a valid number.
I’ve experimented with loops and substrings and such, but my knowledge and understanding is still slim… so any help would be appreciated.
I could build an executable, and I know there are nicer ways to do things than batch files, but at least for this task I’m trying to keep it simple by using a batch file.
Thanks all. I was trying to make it harder for myself looking at loops and string manipulation. I used your tips on math evaluation and comparison. Here’s what I finally came up with as my concept script:
This method catches all numbers and can detect whether it’s positive, negative, or zero. Any decimal or string will be detected as non-integers. The only edge case I’ve found is a string with spaces. For example, the text ‘Number 1’ will cause the script to crash/close when the user input is evaluated as math. But in my situation, this is fine. I don’t want my script to go on with invalid input.