Advertisement
dmilicev

input_only_integer_v2.c

Feb 5th, 2020
307
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | None
  1. /*
  2.  
  3.     input_only_integer_v2.c
  4.  
  5.     Function that allows user to input only integer value.
  6.  
  7.  
  8.     https://www.tutorialspoint.com/cprogramming/c_data_types.htm
  9.  
  10.  
  11.     You can find all my C programs at Dragan Milicev's pastebin:
  12.  
  13.     https://pastebin.com/u/dmilicev
  14.  
  15. */
  16.  
  17. #include <stdio.h>
  18.  
  19. // Function that allows user to input only integer value.
  20. int input_only_integer( char *text, int *integer_number )
  21. {
  22.     int c;
  23.     char terminator;
  24.  
  25.     while(1)                    // an infinite loop that exits with if condition
  26.     {
  27.         printf("%s", text);     // print prompt text
  28.  
  29.         // On success, the function scanf() returns the number
  30.         // of items of the argument list successfully read.
  31.         // If scanf() read two elements, integer and char, and return 2
  32.         // and if second element terminator is enter '\n'
  33.         // then first element is integer.
  34.         if( scanf("%d%c", integer_number, &terminator) == 2 && terminator == '\n' )
  35.             return(*integer_number);
  36.  
  37.         // fflush(stdin);       // flushes the input buffer of a stream,
  38.         // but gives undefined behavior. Alternative is:
  39.         // while ( ( c = getchar() ) != EOF && c != '\n' );
  40.         // or:
  41.  
  42.         while ( ( c = getchar() ) != '\n' );
  43.  
  44.     } // while(1)
  45. } //input_only_integer()
  46.  
  47.  
  48. int main(void)
  49. {
  50.     int integer_number;
  51.  
  52.     input_only_integer("\n Enter integer number: ", &integer_number);
  53.  
  54.     printf("\n Entered integer number is %d \n", integer_number);
  55.  
  56.  
  57.     return 0;
  58.  
  59. } // main()
Advertisement
RAW Paste Data Copied
Advertisement