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

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 :)

1 Answer 1

0

Inside the while loop you need to change the value of 'check1' after using the 'scanf' function.

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);
3
  • What do i change the value to? I tried doing "check1 = scanf(" %d*%c", &a);" inside the while loop to no avail -sorry about the code!
    – Josh
    Mar 12, 2016 at 10:11
  • @Josh, please do not post code in comments. It is unreadable. Mar 12, 2016 at 10:13
  • Thank you this does exactly what I need!
    – Josh
    Mar 12, 2016 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.