如何在'while'循环中重新输入整数值?

时间:2016-03-12 10:04:41

标签: c scanf

printf("please enter a value for side a: ");
check1 = scanf(" %d*%c", &a);
while(check1 != 1)
    {
    printf("You have entered an invalid value");
    scanf(" %d*%c", &a);
    }
printf("The value for A is: %d\n", a);

我试图确保输入的值只是一个整数(check1!= 1)。如果我输入除整数以外的任何内容并且while循环参与,它会无限打印“您输入的值无效”但忽略scanf以重新输入A的值。

我在此之前编写了一段没有(check!= 1)部分的代码,但在while循环中有一个scanf工作。

printf("\nEnter the denominator number: ");
scanf("%d%*c", &num2);
while ( num2 <= 0 )
    {
    printf("The denominator can not be 0 or less, re enter the number: ");
    scanf("%d%*c", &num2);
    }

注意第二段代码可以使用。

我该如何解决这个问题?或者有人可以建议一个简单的替代方法来确保'a'是一个整数?我是编程新手,scanf是我所知道的唯一输入提示。

非常感谢帮助:)

1 个答案:

答案 0 :(得分:0)

在while循环中,您需要更改&#39; check1&#39;使用&#39; scanf&#39;功能

int a; char* w;
printf("please enter a value for side a: ");
int check1 = scanf(" %d*%c", &a);
while (check1 != 1)
{
    scanf("%s", &w);
    printf("You have entered an invalid value\nplease enter a value for side a: ");
    check1 = scanf(" %d*%c", &a);
}
printf("The value for A is: %d\n", a);