How do I re enter an integer value in a 'while' loop?

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: %dn", a);

I am trying to make sure that the entered value is an integer only with (check1 != 1). if I enter anything other than an integer and the while loop engages, it infinitely prints "You have entered an invalid value" but ignores the scanf to re enter the value of A.

I wrote a piece of code prior to this that didn't have the (check != 1) part, but had a scanf inside the while loop that worked.

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

NOTE this second block of code works.

How can I fix this? Or can somebody suggest a simple alternative to making sure that 'a' is an integer? I am very new to programming and scanf is the only input prompt I am aware of.

Help would be much appreciated :)


在while循环中,您需要在使用'scanf'函数后更改'check1'的值。

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 valuenplease enter a value for side a: ");
    check1 = scanf(" %d*%c", &a);
}
printf("The value for A is: %dn", a);
链接地址: http://www.djcxy.com/p/72196.html

上一篇: 在一个结构中,scanf返回的是无效地址

下一篇: 我如何在'while'循环中输入整数值?