c - need an alternative for fflush

寵の児 提交于 2019-12-20 05:38:24

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/47073328/c-need-an-alternative-for-fflush

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!