Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- input_only_integer_v2.c
- Function that allows user to input only integer value.
- https://www.tutorialspoint.com/cprogramming/c_data_types.htm
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- // Function that allows user to input only integer value.
- int input_only_integer( char *text, int *integer_number )
- {
- int c;
- char terminator;
- while(1) // an infinite loop that exits with if condition
- {
- printf("%s", text); // print prompt text
- // On success, the function scanf() returns the number
- // of items of the argument list successfully read.
- // If scanf() read two elements, integer and char, and return 2
- // and if second element terminator is enter '\n'
- // then first element is integer.
- if( scanf("%d%c", integer_number, &terminator) == 2 && terminator == '\n' )
- return(*integer_number);
- // fflush(stdin); // flushes the input buffer of a stream,
- // but gives undefined behavior. Alternative is:
- // while ( ( c = getchar() ) != EOF && c != '\n' );
- // or:
- while ( ( c = getchar() ) != '\n' );
- } // while(1)
- } //input_only_integer()
- int main(void)
- {
- int integer_number;
- input_only_integer("\n Enter integer number: ", &integer_number);
- printf("\n Entered integer number is %d \n", integer_number);
- return 0;
- } // main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement