c-需要另一种替代方法 [英] c - need an alternative for fflush

查看:95
本文介绍了c-需要另一种替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只允许使用标准的c库,所以fpurge()不是我的选择.

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

程序应读入大于1的数字,并且如果存在字母之类的任何错误"输入,则程序应继续发送错误消息.在我的Windows pc上,它可以与fflush一起使用,从而使程序应在Linux系统上运行.

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.

如何替换程序仍然可用的fflush?因为当我不使用它时,我会陷入无限循环.

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.

推荐答案

您可能想要这样的东西:

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

在调用strtol后,endptr指向输入的第一个非数字字符.如果仅输入数字,endptr将指向终止行的\n,否则例如已输入12xendptr将指向'x'.

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'.

您可以通过编写GetNumber函数来改进此功能,这样您就可以编写

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

dim = GetNumber();

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

这篇关于c-需要另一种替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆