c - need an alternative for fflush

扶醉桌前 提交于 2019-12-02 12:24:23

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