Search code examples
cfflush

c - need an alternative for fflush


I am only allowed to use the standard c library so fpurge() is not an option form me.

int dim = 0;
int c = 0;

printf("Please enter a number");

while ( (( c = scanf("%d",&dim)) != 1 ) || (dim < 1) || (dim > UCHAR_MAX) )   
{
    if (c == EOF)
    {
        return 0;
    }
    fflush(stdin);
    printf("[ERR] Enter a number\n");
    printf("Please enter a number");
}

The program should read in a number big than one and if there is any “wrong” input like letters it should go and deliver an error message. It works with fflush on my windows pc put the program should run on a Linux system.

How can I replace fflush that the programm still works? Because when I do not use it I come in an infinite loop.

The number which is entered determines how often a certain line of code is used in the rest of the program that is why I need an array.


Solution

  • You probably want something like this:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
      int dim = 0;
    
      for (;;)
      {
        printf("Please enter a number: ");
        char buffer[30];
        fgets(buffer, sizeof(buffer), stdin);
    
        char *endpointer;
        dim = strtol(buffer, &endpointer, 10);
    
        if (*endpointer != '\n' || (dim < 1) || (dim > UCHAR_MAX))
        {
          printf("[ERR] Enter a number\n");
          continue;
        }
        break;
      }
    
      printf("The number you entered is: %d\n", dim);
    }
    

    After the call to strtol, endptr points to the first non digit char entered. If only digits have been entered, endptr will point to the \n that terminates the line, otherwise if e.g. 12x has been entered, endptr will point to the 'x'.

    You may improve this by writing a GetNumber function so you can just write

    dim = GetNumber();
    

    or

    dim = GetNumber("Please enter a number: ", "[ERR] Enter a number\n", 1, UCHAR_MAX);