0

I have a question about how to compare strings in an if statement. I am moving from Python to C and the comparing strings is easy in Python, but in C how do I do it?

My program is:

printf("Enter your choice 1.add\n 2.sub\n 3.mul\n 4.div\n");
string choice = get_string();

if (choice == "add")
{
    int c = calculate_add(a, b);
    printf("sum of %i and %i is %i\n", a, b, c);
}

When I run this, I get this error:

calculate.c:19:16: error: result of comparison against a string literal is
  unspecified (use strncmp instead) [-Werror,-Wstring-compare]
if (choice == "add")
           ^  ~~~~~

It says use strncmp to compare the string, but how do I do it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pkarthicbz
  • 93
  • 2
  • 10
  • 1
    Is this line correct string choice = get_string();? – kourouma_coder Mar 27 '17 at 01:10
  • "_but i don't know how to do it_" - Google, research and learn. There are a lot of examples in the web. Did you check them out? – Spikatrix Mar 27 '17 at 01:26
  • @lazy_coder ya that's correct because i included cs50 header file :) – pkarthicbz Mar 27 '17 at 13:51
  • @CoolGuy that's good advice but stack is way more better than google :) – pkarthicbz Mar 27 '17 at 13:55
  • @pkarthicbz Yes, but for these kind of beginner questions, use google. There are a lot of examples you can get from there. If you read the tooltip of the downvote button, you'll see something like 'Post has shown no research effort'. People will downvote. That's to keep up the good quality of questions. You could've found out how to use `strcmp` much faster if you had googled it. Consult Stack Overflow only _after_ your research fails you. – Spikatrix Mar 27 '17 at 13:59

2 Answers2

2

Simply instead of

if(choice == "add")

use the following syntax:

if(!strcmp(choice, "add"))

Don't forget to include <string.h>.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user7771338
  • 185
  • 6
1

Use strcmp from <string.h>

#include <string.h> // It might compile without it, but always add it for portability and so that your code compiles in all compilers that follow the C standard.

int main() {
   int equals = strcmp("add", "add") == 0; // equals = true

   int greaterThan = strcmp("bad", "add") > 0; // greaterThan = 1

   int lessThan =  strcmp("123", "add) < 0; // lessThan < 0

}

So in your case:

if (strcmp(choice, "add") == 0) { // This means choice = "add"
    int c = calculate_add(a, b);
    printf("sum of %i and %i is %i\n", a, b, c);
}
Santiago Varela
  • 2,199
  • 16
  • 22