Monday, January 18, 2010

How can i control input in c language?

hello there! is anyone there who knows how i can control input in c? for example when i want the user to give an integer i want to make sure he won't give a float number or a character so that the program won't stuck.please don't give me links to other pages. answer only if you know and clearly. thanks!How can i control input in c language?



C provides us with a function, isdigit, in its ctype library, for determining whether a character is a decimal digit or not. It takes a character as an argument (not a pointer to a character!). Its return value is an int which tells us whether the given character was a digit or not. This return value follows the convention for all C functions that return a true/false answer. A return value of 0 signifies ';false';, whilst any other return value signifies ';true';. Such a value is called a boolean value.





you can perform with isdgit() in %26lt;ctype.h%26gt;.





Sample Example








#include %26lt;ctype.h%26gt;


#include %26lt;stdio.h%26gt;





int getch(void);


void ungetch(int);





/* getint: get next integer from input into *pn */


int getint(int *pn)


{


int c, sign;





while (isspace(c = getch())) /* skip white space */


;





if (!isdigit(c) %26amp;%26amp; c != EOF %26amp;%26amp; c != '+' %26amp;%26amp; c != '-') {


ungetch(c); /* it is not a number */


return 0;


}


sign = (c == '-') ? -1 : 1;


if (c == '+' || c == '-')


c = getch();


for (*pn = 0; isdigit(c); c = getch())


*pn = 10 * *pn + (c - '0');


*pn *= sign;


if (c != EOF)


ungetch(c);


return c;


}

No comments:

Post a Comment