Question:
restricting input in c?
bash
2006-06-21 06:38:28 UTC
i have a small C program to tell if input is even or odd. idealy, the user should enter numbers but when the cheeky ones enter characters, they get results saying "even number". is there a way to stop entry of a character instead of a number without using an elaborate conditional statement???
Three answers:
Neil
2006-06-21 07:19:04 UTC
1st the answer you are looking for.

Try something like this

----------------------------------------------------------

#include



int main() {

int x, temp, length;

char input[10];

while(1) {

x=0;

printf("Please enter a number\n");

fgets(input, 9, stdin);

length=strlen(input);

for(temp=0;

((temp
temp++) {

if ((input[temp]-'0'<0)||(input[temp]-'0'>9)) {

x++;

}

}

if(x!=0) {

printf("Invalid entry. A number was expected\n");

} else {

break;

}

}

}

----------------------------------------------------------



2ndly, its extremely vital to check for user input and validate its authenticity. You may find that uninteresting but only when you do such stuff can you write software and not just code.
crgrier
2006-06-21 14:13:00 UTC
You can take advantage of the facts that a string is stored as an array of characters and that C stores characters as integers. Loop through the string and test each character to see if it is in the correct range on the ASCII table (48 - 57).
sheeple_rancher
2006-06-21 16:02:27 UTC
Here is a function to get a number while filtering out everything else "live" on the console.

It compiles and runs on linux. On Windows, you would use the conio.h functions kbhit() and getch() rather than the system() calls.



#include

#include





/* getNumber(*input) returns true for valid numeric input.

** input is unchanged if there is no numeric input.

** Filters at the character io level.

** Tested on linux + gcc.

*/



int getNumber( int * input )

{

char ln[40]; /* Room for big number as text */

char *pi;

int ch;



pi = &ln[0]; /* input pointer */

ch = 0;

*pi = 0;



system("stty raw"); /* Suppress line buffering */



while( (ch != '\n') && (ch != '\r') ) /* EOL */

{

ch = getchar();

if( isdigit( ch ) )

{

*pi++ = (char)(ch);

*pi = 0;

}

else

if( (ch == '\n') || (ch == '\r') )

{

putchar( ch );

if( input != 0 )

*input = strtol( ln, 0, 10 );

}

else

if( ch != 0 ) /* Kill that char */

{

putchar( '\b' );

putchar( ' ' );

putchar( '\b' );

}

}

system("stty cooked"); /* Restore */



if( strlen( ln ) == 0 ) /* no input */

return 0;

else

return 1;

}



/*-- Example use --*/



int main()

{

int x;

printf("Enter a number\n>");

if( getNumber( & x ) )

{

printf( "You entered %d\n", x );

}

else

{

printf( "No candy for you.\n");

}

return 0;

}



WARN: Inside the 'if( isdigit( ch ) )' block, you will want to count characters input and exit before the ln[] buffer overflows.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...