0

I'm making a simple menu program (adapted from example in "C programming in easy steps", M.McGrath, pg74), however when running the program the again() function does not scan for a character, it prints and then automatically chooses the else command in the function. It does not return to menu() when Y or y are chosen. The program works as expected when ag is an integer and not a character. How can this be rectified?

#include <stdio.h>

void menu ();
void getnum ();
void getnums ();
void again ();
int square (int x);
int multiply (int x, int y);

int
main ()
{
  menu ();
  printf ("End \n");
  return 0;
}

void
menu ()
{
  int num;
  printf ("\n Enter the number of an operation.");
  printf ("\n1. Square a number.");
  printf ("\n2. Multiply two numbers.");
  printf ("\n3. Exit.\n");
  scanf ("%d", &num);
  switch (num)
    {
    case 1:
      getnum ();
      break;
    case 2:
      getnums ();
      break;
    case 3:
      return;
    }
}

void
getnum ()
{
  int num;
  printf ("\nEnter a number to be squared:");
  scanf ("%d", &num);
  printf ("%d squared is %d.", num, square (num));
  again();
}

void
getnums ()
{
  int num1, num2;
  printf ("\nEnter two numbers to be multiplied, seperated by a space:");
  scanf ("%d", &num1);
  scanf ("%d", &num2);
  printf ("%d multiplied by %d is %d.", num1, num2, multiply (num1, num2));
  again ();
    }

int
square (int x)
{
  return (x * x);
}

int
multiply (int x, int y)
{
  return (x * y);
}

void
again ()
{
   int ag;
   printf ("\nPerform another opperation? Y or N");
  scanf ("%c" , &ag);
  if ((ag == 'Y') || (ag == 'y'))
    menu ();
  else
    return;
}
  • Do you understand that `scanf` returns a value? – Ed Heal Jul 28 '18 at 19:39
  • This question has been asked ***many*** times. The `scanf` format specifier `%c` reads *everything* including whitespace whereas the `%d` format specifier filters out leading whitespace. You should add a space before `%c` such as `scanf(" %c",&ag);` to force `%c` to do that. – Weather Vane Jul 28 '18 at 19:50

0 Answers0