-2

I am fully aware that this is due to some error overlooked by me while writing my text-based calculator project in C, but I have only started learning C less than a week ago, so please help me out!

Since the entire code is 119 lines, I'll just post the necessary snippet where the real issue lies: (There are no errors during compiling, so there is no error beyond these lines)

char choice[15];
    printf("Type 'CALCULATE' or 'FACTORISE' or 'AVERAGE' to choose function :\n");
    gets(choice);
    if (choice == "CALCULATE")

The bug is that even after perfectly entering CALCULATE or FACTORISE or AVERAGE, I still get the error message that I programmed in case of invalid input (i.e, if none of these 3 inputs are entered). It SHOULD be going on to ask me the first number I wish to operate on, as written for the CALCULATE input.

The code runs fine, no errors in VS 2013, and so I'm sure its not a syntax error but rather something stupid I've done in these few lines.

avocadoLambda
  • 1,332
  • 7
  • 16
  • 33
An Ant
  • 184
  • 1
  • 10

3 Answers3

0

If you use == you are comparing the addresses of 2 arrays, not the contents of the arrays.

Instead, you need to do:

if (strcmp(choice, "CALCULATE") == 0)
cigien
  • 57,834
  • 11
  • 73
  • 112
  • Thanks, that should fix it. I havent studied arrays yet, I was just going by what I had learnt from Python. – An Ant Jun 15 '20 at 05:25
  • I'm not sure what you're question is, but that should be a separate question. – cigien Jun 15 '20 at 06:29
0

Two things to mention here:

  1. Never use gets() it has serious security issues and is removed from the latest standard. Use fgets() instead.
  2. To compare strings, you should use strcmp(), not ==.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • fgets() avoids buffer overflow, true, but increases unnecessary steps, and to be real, it is mostly only me who will use this project. – An Ant Jun 15 '20 at 05:26
  • @AnAnt Whatever be the case, if you want to write correct and standard complaint code, you **cannot** use `gets()`. – Sourav Ghosh Jun 15 '20 at 05:27
  • I'm coding for myself, and i respect you standardised instincts, but for me and 4 of my friends it really wouldnt matter that much right ? – An Ant Jun 15 '20 at 05:32
  • @AnAnt take your pick, but I'd suggest, if you're doing something, do it right. – Sourav Ghosh Jun 15 '20 at 05:34
0

The problem is you're trying to compare a string literal with a char array. C isn't found those things being the same, since the '==' comparison operator is not implemented in that way.

You have two options for performing that comparison :

1) Use the strcmp() function, from string.h library

2) Manually comparing the chars in your array, and the string literal

Definitely, the first option is the easiest and cleanest one.