C - Getting input from user

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

C - Getting input from user

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

scanf a string, "analyze" the string to see if it's numeric.
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

should be able to ask it to only read that many characters.
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

Post by nigma »

Alright, I see what your saying. I gave it a shot and things worked like a charm ;)
Post Reply