0

I have a code that if the user key in "what is apple" it should answer "apple is a fruits" but for this case the what is stored as [what] in a text file. Look like this

[what]
apple = apple is a fruits.

below is my codes. It doesnt print out " apple is a fruits". Can i know where is my error?

char intent[255];
char key1[255];
char key[255];
char inv[3][10] = { "what","where","who" };

snprintf(intent, sizeof(intent), "[%s]", inv[0]);
printf("%s\n", intent);

scanf("%s",&key1);

if (strcmp (intent == "[what]" && key == "apple") == key1) {
    printf ("apple is a fruits");
    }
kelly
  • 21
  • 3
  • 4
    That's not how you compare strings in C. – Shawn Nov 22 '19 at 00:52
  • 5
    http://c-faq.com/charstring/stringeq.html – Shawn Nov 22 '19 at 00:53
  • Hi, I have edited the codes but it doesnt work and there is error " Access violation reading location 0x00000000 " – kelly Nov 22 '19 at 01:01
  • The code as modified should not compile — `strcmp()` requires two arguments, and you provide just one. You should be using `strcmp(intent, "[what]") == 0 && strcmp(key, "apple") == 0` as the condition to compare two pairs of strings. – Jonathan Leffler Nov 22 '19 at 01:04
  • 1
    You should learn from a reference, rather than trial and error – M.M Nov 22 '19 at 01:07
  • There are other issues with your code that will cause it to not run as intended. The usage of & in scanf and the misuse of snprintf. Check my response for more – Jimmy Potter Nov 22 '19 at 01:09

1 Answers1

0

As Shawn said in his comment to your question, you can't compare C strings using the == operator, you need to use the strcmp() function.

Also, the second parameter of snprintf should be the number of chars that should not be exceeded by the function, which isn't what sizeof(intent) does. sizeof(intent) wouldn't give you the size of the intent array, but return the size of a char* pointer, if I'm correct. Just replace sizeof(intent) with 255 or use a constant MAXSIZE for it.

Also, scanf doesn't need the & operator when writing to char arrays (ie strings), scanf("%s", key1); is correct, as the name of an array is the address.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • In this case since `intent` is an array, not a pointer, `sizeof(intent)` is 255 and using it is appropriate. – Shawn Nov 22 '19 at 01:15