如何从输入不正确输入prevent用户

如何从输入不正确输入prevent用户

本文介绍了如何从输入不正确输入prevent用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序要求的数字。该方案应循环 scanf()的功能如果用户键入别的以外的号码。

在code是,

  {做
     的printf(请输入行数\\ n);
     scanf函数(%d个,&安培;排);
  }而(行> ='A'和;&安培;排< ='Z');

但上面的code不起作用。在信中打字的时候我总是收到一个错误。我试图操纵绕过它,整个事情无限循环。

有什么建议?

另外我怎么能告诉 C编译器不打破循环,除非输入是INTEGER?


解决方案

您所忽略的从返回scanf函数(它告诉你输入的信息是否是准确的转化率(%d个)或不。如果是不准确的,你要做的错误恢复,这是特别不容易与 scanf()的。大多数人去的读一行输入,然后分析它的做法是,如果错误恢复更加简单。


This is why people don't use scanf(). If you get the line of data into a buffer (character array), then you can check the contents of the array as often as you like. If you use scanf(), you don't get a reliable chance to process the data until after scanf() decides it has an error.

The functions (usually also available as macros) in <ctype.h> allow you to classify characters. The functions in <stdlib.h> provide reliable conversions from strings to integers of various sorts.

So, you can think about doing something like:

char buffer[256];

while (fgets(buffer, sizeof(buffer), stdin))
{
    ...check contents of buffer using isdigit() etc...
    ...or just plough ahead with...
    long value;
    char *end;
    errno = 0;
    value = strtol(buffer, &end, 0);
    if (errno != 0 || (*end != '\0' && !isspace(*end))
        ...diagnose problems...
}


Well, I suppose you can use atoi() instead of strtol(), which simplifies the error handling (because it is less precise):

char buffer[256];

while (fgets(buffer, sizeof(buffer), stdin))
{
    int value = atoi(buffer);
    if (value == 0)
    {
        puts("zero read - exiting loop");
        break;
    }
}

It doesn't get much simpler than this. I don't know which part of the previous solution you felt was beyond you. The alternatives, it seems to me, are much fiddlier, involving reading one character at a time and saving the digits and rejecting the non-digits:

char buffer[256];
char *dst = buffer;
int c;
int value;

while ((c = getchar()) != EOF)
{
    if (isdigit(c))
    {
        *dst++ = c;  /* Ignoring buffer overflow - bad! */
    }
    else if (isspace(c))
    {
        *dst = '\0';
        value = atoi(buffer);
        break;
    }
    else
    {
        printf("Unexpected character '%c'!\n", c);
    }
}

Etcetera. There are various issues to resolve in that code - like resetting the pointer after an erroneous character, and avoiding buffer overflow, and dealing with signs on the numbers, and ... well, all sorts of stuff that I'd rather leave to routines like fgets() and strtol().

这篇关于如何从输入不正确输入prevent用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 16:34