使用getchar()验证1-9之间的用户输入

时间:2016-01-26 21:13:47

标签: c

嘿伙计们我试图编写一个小程序,用户必须在1-9之间输入一个数字,其他任何东西都是错误的,但是我在验证输入时遇到了问题,因为如果你输入12它只读取1,它进入循环。它必须使用getchar()完成,这是迄今为止所做的:

 printf(%s,"please enter a number between 1 - 9);
 int c;
 c = getchar();
    while(c != '\n') {

    int count = 1;
    count ++;

    if ((c >= '0' && c <= '9') || count > 1) {
 printf(%s, "Congrats!);
 }
 else
 {
 print(%s, "ERROR);
    }

 }

我在进入int时将char验证为int也有问题。如果我输入5,我得到53.

4 个答案:

答案 0 :(得分:1)

尝试更改计数&gt; 1到count == 1,并将其初始化为0而不是1.这样你就可以保持你拥有的位数。另请注意,因为您将count初始化为1然后立即递增,所以计数&gt; 1将永远评估为真,所以如果你给它任何一个字符,它总是说它是正确的。

答案 1 :(得分:1)

getchar()将返回键入的下一个字符。如果你想要的不止是第一个字符,你需要在while循环中再次调用getchar()。

//Somewhere to store the result
//initialized with an invalid result value
int digitchar = 0;

//Get the first char
int c = getchar();
while (c != '\n')
{
    //Check if we already have a digit
    //and that the new char is a digit
    if (digitchar == 0 && c >= '1' && c <= '9')
    {
        digitchar = c;
    }


    //Get the next char
    c = getchar();
}

//Check if we have stored a result
if (digitchar != 0)
{
    //Success
}

请注意,如果输入了非数字或换行符,则无法处理。您需要将其作为错误处理,以及输入多个数字。

答案 2 :(得分:0)

这不适用于12,因为getchar()每次需要一个字符。以下示例是解决它的一种方法。

event.target.innerHTML

答案 3 :(得分:0)

请记住,getchar()返回char的ascii值,因此当您将值传递给函数时,必须减去char'0'以将实际的十进制值传递给函数。 另一点是你必须清除输入缓冲区。如果用户输入了错误的输入,则必须确保在尝试再次读取输入之前输入缓冲区中没有任何内容。 希望这可以帮助。

int main(void) {

    int input = 0; // 0 is the sentinel value to close program   

    printf("\n%s\n", "Enter value between 1-9 .\nEnter [0] to finish.");

    do {
        input = getchar();

        if (((input>= '1') && (input <= '9') || input == '0') && getchar() == '\n') {

            if ((input >= '1') && (input <= '9')) {
                callYourOwnFuntionAndPassValue(input - '0');
                printf("\n%s\n", "Enter value between 1-9 .\nEnter [0] to finish.");
            }
        } 
        else {
            while (getchar() != '\n') {} // clear input buffer
            printf("\n%s\n", "Please enter a valid number");
        }

    } while (input != END_PROGRAM);


    return NO_ERROR; // NO_ERROR  = 0
}
相关问题