3

I'm trying to write a program that involves comparing chars as part of a menu system for a program that decodes resistor codes. At the end of the menu it asks if you want to decode another resistor, repeating the program if the user selects "yes".

This is the code I have so far:

  //used for repeating input menu
  int menu = 0;
  char menuChoice = 0;

  //rest of program goes here      

  printf("Do you want to decode another resistor? (y/n)");
  scanf("%c", &menuChoice);

  while(menuChoice != "y" && menuChoice != "Y" && menuChoice != "n" && menuChoice != "N")
  {
    if(menuChoice != "Y" && menuChoice != "y")
    {
      if(menuChoice == "N" || menuChoice == "n")
      {
        menu = 0;
      }

      else
      {
        printf("Invalid choice.");
      }
    }
  }

When I try to compile with GCC, I end up with a warning that says "comparison between pointer and integer." Since scanf only accepts a pointer, I don't know how exactly to compare the scanned char with to "Y" or "n". Is there something I'm missing here?

user2309750
  • 1,403
  • 4
  • 14
  • 11
  • 10
    character literals need the char_literal character eg. `'y'` not `"y"` – amdixon Nov 23 '13 at 23:10
  • And the reason you get the confusing error message about a pointer is that a string literal is of array type, and an array expression is, in most contexts, implicitly converted to a pointer to the array's first element. So `menuChoice != "Y"` attempts to compare the integer value `menuChoice` (`char` is an integer type) to the pointer value that results from the implicit conversion of `"Y"` to `char*`. The comparison doesn't make any sense. In fact I find it disappointing that gcc merely warns about it; it could, and IMHO should, treat it as a fatal error. – Keith Thompson Nov 24 '13 at 00:33
  • @KeithThompson if gcc started giving errors for implicit pointer-integer conversions it might wake up a bunch of people to fix their old code – M.M Mar 15 '15 at 23:45

2 Answers2

2

You are using the string literal syntax "a" instead of the char literal syntax 'a'

More about the difference

Community
  • 1
  • 1
horns
  • 1,843
  • 1
  • 19
  • 26
0

Adjust your comparisons. Presently they compare a an integer (or char such as menuChoice) to an array (such as "y").

// menuChoice != "y"
menuChoice != 'y'

The while(menuChoice != "y") && ...) likely should be removed.

The if(menuChoice == "N" ... should be else if(menuChoice == "N" ...).

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256