I am currently writing a simple program that will either allow me to add music or show all of my albums, artists, and songs. The program starts in main(); then after selecting "View Music" it goes to the viewMusic() function but runs through the function and skips the getchar() for the next selection.

I tried messing around with it and found that if I write getchar() twice it will do what I want. But this obviously isn't good coding. Is there some sort of memory issue or bad function calling that I'm not aware of?

#include <stdio.h>

int main (void)
{
  char action;
  printf("Welcome to the music database.\n\n");
  printf("What do you want to do? (v - View, e - Enter Data)\n");

  action = getchar();

  switch (action)
  {
  case 'v':
     printf("\nViewing Music\n");
     viewMusic();
     return 0;
     break;
  case 'e':
    printf("\nEntering Data\n");
    enterMusic();
    return 0;
    break;
  default:
    printf("\nInvalid Entry\n\n");
    main();
    return 0;
    break;
  }
}

viewMusic()
{
  char action;
  printf("View by: [a] Album, [r] Artist, [s] Song\n");

  action = getchar();

  switch (action)
  {
  case 'a':
    printf("Displaying By Album\n");
    break;
  case 'r':
    printf("Displaying By Artist\n");
    break;
  case 's':
    printf("Displaying By Song\n");
    break;
  default:
    printf("Invalid\n\n");
    viewMusic();
    return 0;
    break;
  }
}

When I run the code and go to viewMusic() it runs through the function and spits out "Invalid" and then runs the viewMusic(). Once I get to viewMusic() the 2nd time I can actually select my option.

Any clue why it runs through the viewMusic() function without me being able to make a selection the 1st time?

Your input stream is still holding the newline char. Remove it by adding this:

(void) getchar();

After each time you're looking for a char input (getchar or scanf(%c)).

fflush(stdin) is non-standard, and generally doesn't work, because stdin is an input stream, not an output stream.

And Welcome to the forum, Caeon! ;)

Edited 6 Years Ago by Adak: n/a

Thanks! Works perfect!

Would this be considered good coding standards? I am new to C and it seems like there should be a better way. But as I've been learning it seems that most what "should" and "are" are two different things. =P

Again, thanks for the help. Much appreciated.

I prefer using fgets(charArrayName, sizeof(charArrayName), stdin); with
sscanf("%c", &charVariable);, generally.

In this case, it's no better. I seldom use getchar() except to pull newlines off the input stream to clean it up, so I'm not the best person to ask this.

I tend to use what's simple, and works, and let the "right" and "wrong" take care of themselves.

You're very welcome!

This question has already been answered. Start a new discussion instead.