423,682 Members | 1,327 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 423,682 IT Pros & Developers. It's quick & easy.

Hello, i would love to compare a number of strings, but strcmp allows me to only comp

P: 1
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include<strings.h>
  5.  
  6. int main(){
  7.     char Entry[10];
  8.     char Delete[10] = "Delete";
  9.     char Reverse[10] = "Reverse";
  10.     char Double[10] = "Double";
  11.     char Replace[10] = "Replace";
  12.     char Decrypt[10]="Decrypt";
  13.     char Encrypt[10]="Encrypt";
  14.     char Quit[10] = "Quit";
  15.     char str[10];
  16.  
  17.     scanf("%s,%s,%s,%s",Double,Delete,Reverse,Replace);
  18.  if (strcmp(Entry,Double)==0 && strcmp(Entry,Delete)==0 && strcmp(Entry,Reverse)==0 && strcmp(Entry,Replace)==0)
  19.  {
  20.  
  21.  printf("\nyes");
  22. }
  23.  else printf("\ninvalid inputs!");
  24.  
  25.     return 0;
  26. }
Jul 25 '18 #1
Share this Question
Share on Google+
3 Replies


weaknessforcats
Expert Mod 5K+
P: 9,186
I am not sure what you need to do.

However, strcmp returns 0 when the strings are equal. A 0 is false. Therefore, you need to use the not operator (!) when using strcmp inside an "if" statement:

Expand|Select|Wrap|Line Numbers
  1. if (!strcmp(strA, strB))
  2. {
  3.    printf("strings are equal\n");
  4. }
Jul 25 '18 #2

P: 27
You can use nested ifs to compare several strings using strcmp. Like:

Expand|Select|Wrap|Line Numbers
  1. if(!strcmp(A, B)){
  2.    if(!strcmp(A, C)){
  3.        //Print strings A, B and C are equal
  4.    }
  5. }
  6.  
Aug 18 '18 #3

Expert 100+
P: 2,384
scanf() on line 17 overwrites strings Double, Delete, Reverse, and Replace; so the initializers on lines 8-11 are useless.

If you donít intend for the strings on lines 8-14 to be changed then you should declare them as const char arrays. If these strings are const then there is no need to specify the array size ó use empty brackets([ ])

The Entry array is uninitialized.

Do you perhaps want || (or) instead of && (and) on line 18? Entry can only be equal to Double, Delete, Reverse, and Replace if somehow those 4 strings are equal to each other.

Lines 21 and 23. Might be best to add newline to the end of each printed string.

Line 23. I suggest you braces around the printf() like you have on lines 19-22 so you donít get confused about what happens here.

Lines 19-23. Indentation is inconsistent with rest of function. This might cause confusion.
Aug 21 '18 #4

Post your reply

Sign in to post your reply or Sign up for a free account.