Page 1 of 1

C - Getting input from user

Posted: Sun Sep 26, 2004 8:08 pm
by nigma
Hey, say I have the following code:

Code: Select all

printf("Enter a number: "); 
scanf("%f",&float_var); // float_var is of type float
How can I keep my program from going berzerk if the user enters say a character?

Posted: Sun Sep 26, 2004 8:31 pm
by feyd
scanf a string, "analyze" the string to see if it's numeric.

Posted: Sun Sep 26, 2004 9:18 pm
by nigma
You put analyze in quotes, is that because there isn't a function to do this for you?

Also, you said "scanf a string", did you mean like so?

Code: Select all

char stringї20];
scanf("%s",string);
Thanks for the help.

Posted: Sun Sep 26, 2004 9:24 pm
by feyd
sorta.. there's atof which will attempt to convert an ascii string into a float for you.

as for scanf'ing a string, yes that's the way. Although I remember getting a 0 (in the float) if the input was a non-numeric.

Posted: Sun Sep 26, 2004 9:59 pm
by nigma
How about keeping an error from occuring when the program tries to cram 25 user entered chars into an array of only 20 chars?

Posted: Sun Sep 26, 2004 10:03 pm
by feyd
should be able to ask it to only read that many characters.

Posted: Sun Sep 26, 2004 10:09 pm
by nigma
Alright, I see what your saying. I gave it a shot and things worked like a charm ;)