By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,433 Members | 1,797 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,433 IT Pros & Developers. It's quick & easy.

control input in c

P: 1
hello there! i am new in c. i have been searching for a long time how i can control input in c. for example if i want the user to enter an integer (no matter how many digits) and not a character or a float what can i do (so that the program won't stuck)? please help with an example explaining every command you write. thanks a lot.
Nov 15 '08 #1
Share this Question
Share on Google+
3 Replies

Expert 10K+
P: 11,448
FIrst bookmark this link and read it. It contains a reference
to the entire C Standard library.

As a rule of thumb: when the user types something the program didn't anticipate
for, prompt the user and get rid of the erroneous input and try again.

How exactly you want to do this is all up to you. Manual user input can be
really messy and complicated when you don't do it consistently.

If you do it right turn your code into a 'utilities' library ready for later use.

kind regards,

Nov 15 '08 #2

Expert Mod 5K+
P: 8,916
Under no circumstance use scanf. It is a very bad function.

My approach is always to use fgets to get input from the user as a character string, remove trailing whitespace and then to parse the string using strtoul, strtol or strtod depending on what type of input I am looking for.

Those functions provide an easy way to tell if the user has input anything they shouldn't have done.

You can find all those functions in the reference Jos has provided a link to.
Nov 15 '08 #3

P: 152
I agree... use fgets() and strtod() (or what function you want from that 'family').
However, you tell fgets() how any characters to receive from a stream; so do something to remove extra input entered from user that fgets did not get (you might not want to however). Oh, do not do fflush( stdin ); it is not portable.
Nov 15 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.