![]() |
|
#1
|
|||
|
|||
Need Help on checking user inputHow do you check to see if the user enter invalid input ?
I am doing a program that only except input as integer ..... if the user input float or alphabet the program will reprompt the user to input integer..... How do you check to see if the user input integer or not ? Thank You! |
|
#2
|
|||
|
|||
|
Well how are you going about recieving the input?
If you use scanf, giving it the correct placeholder will cause it to only take what input it's been given,. e.g for to place an integer in input: CPP / C++ / C Code:
CPP / C++ / C Code:
If you're using C++, just defining an int, and using the << operator, it'll recieve the first integer the user inputs. Any good? GF |
|
#3
|
||||
|
||||
|
Quote:
|
|
#4
|
|||
|
|||
|
Someone once told me that "real programmers don't use scanf()". (Since
it's not very good at handling real-world input, which can have errors.) Here's a suggestion for C programs: Use fgets() to read an input line from the user into a char array, then write a routine that steps through the array, looking for whatever it is that you require (nothing but decimal digits, in your case). If the user has done something illegal, you can ask him/her to try again, or you can bail out of the program (with a polite message telling the user what you expect), or ... Once you verify that the input consists of decimal digits, then convert to an integer, using whatever program device you want (write a routine yourself, or use sscanf() or atoi() or anything else that comes to mind). Dave |
|
#5
|
|||
|
|||
|
Quote:
Very true, but best to keep things simple for beginners. Scanf is the easiest to get a hang of, corresponds to printf, and does type conversion automatically. Once a beginner progresses, and finds all of scanf's "quirks" (or bugs more like) (s)he'll abandon it soon enough. GF |
|
#6
|
|||
|
|||
|
Quote:
case he specifically said Quote:
If this is a class assignment, I don't see how he can satisfy it with scanf(), since a user input of, say 12.34, stores the integer value 12 in the target variable, (and doesn't complain). |
Recent GIDBlog
Writing a book by crystalattice
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Win2k domain user dont appear in WinNT domain | VoooDooo | Computer Software Forum - Windows | 5 | 18-Feb-2004 08:55 |
| a C input question.. | tmike | C Programming Language | 2 | 19-Sep-2003 03:39 |
| a C input question | tmike | C Programming Language | 1 | 16-Sep-2003 03:31 |
| Script needed for letting user input a few days of data for tracking and analysis. | tradertt | MySQL / PHP Forum | 3 | 06-Mar-2003 03:54 |
Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The