Orkay
Orkay

Reputation: 11

C Program While Loop problem

I have a program to write and it is giving me trouble.

It asks the user for inputs such as suggesting which shape they would like to know the area and/or surface are of. This element, I have mastered.

The problem is that when I try to add in while loops to say that the response is invalid, it messes the whole program up.

I need it to say, "Invalid response, please select option 1, 2 3 or 4 etc.

I am writing the loop as follows:

printf("Please enter 1 for area or 2 for surface area: ");
scanf("%i",&menu1);
while(menu1!=1&&menu1!=2) {
  printf("Invalid option. Please enter 1 for area or 2 for surface area: "); 
  scanf("%i",&menu1);
}

The problem is now when the user makes a valid response, "Invalid response" appears. How to fix this?

Upvotes: 1

Views: 1826

Answers (1)

KChaloux
KChaloux

Reputation: 4028

The following works for me:

#include <stdio.h>

int main(void) {
  int menu1; // Make sure this is declared 

  printf("Please enter 1 for area or 2 for surface area: ");
  scanf("%i", &menu1);

  while((menu1 != 1) && (menu1 != 2)) {
    printf("Invalid option. Please enter 1 for area or 2 for surface area: ");
    scanf("%i", &menu1);
  }

  return 0;
}

You didn't post the entirety of your code, but I'm assuming that you didn't declare menu1 before using it in scanf. That would certainly cause issues.

Update

As pointed out by @John in the comments, you can eliminate some redundancy by using a do-while to make sure the loop always runs at least once.

As @Cqnqrd notes, scanf can cause some infinite looping problems if you enter non-integral values, the reasons for which are detailed here. You can use fgets and atoi to handle non-integer input better than scanf does (preventing an infinite loop on an input of something like 'aa').

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  int menu1 = 0;
  char input[256];

  do {
    printf("Please enter 1 for area or 2 for surface area: ");
    fgets(input, 256, stdin);
    menu1 = atoi(input);

    if ((menu1 != 1) && (menu1 != 2)) printf("Invalid entry. ");
  } while ((menu1 != 1) && (menu1 != 2));

  return 0;
}

Upvotes: 3

Related Questions