C++ How do I compare two char arrays?

You need to enter a group. Next, iterate through the structure, find an entry with a matching group, and output it.

struct TZap{        
     char n_group[5];
     } Zap;
  char kodG[5];
  scanf("%s", &kodG);            // ввод группы для сравнения
  for (i=0; i < kol-1; i++) {     // Цикл перебора 
    if(mas_Z[i].n_group == kodG) { // Проверка на совпадение
      Out(mas_Z[i]);               // Передает в функцию запись для вывода 
    }
  }

I did a check, the loop is executed the required number of times, but the condition is never executed at all.

Why can't I make a comparison mas_Z[i].n_group == kodS?

P.S. Introduced a small misunderstanding with kodS. All because of my inattention. kodS replaced with kodG.

UPDATE

if(strncmp (mas_Z[i].n_group, kodG,1)==0)     
    puts ("TRUE"); 
else   
    puts ("FALSE");

Returns "TRUE". If you use strcmp:

strcmp(mas_Z[i].n_group, kodG);

Returns 0. This is a positive test result

Author: Kyper, 2018-12-29

2 answers

  1. Using the & operator with the %s format in scanf is almost always an error

    scanf("%s", &kodG);  
    

    What is this & doing here?

    Or

    scanf("%s", kodG);  
    

    Or (if you like)

    scanf("%s", &kodG[0]);  
    

    But by no means what you have. "In practice" your version may work, but this is not a reason to write such a thing.

  2. Using an array as small as 5 for user input via scanf("%s" is a serious buffer overflow claim. all the consequences. Do at least

    scanf("%4s", kodG);  
    
  3. Comparison of C-strings in C++ is done in the same way as in C: function strcmp.

    if (std::strcmp(mas_Z[i].n_group, kodG) == 0)
    
  4. Why can't I make a comparison mas_Z[i].n_group == kodG

    Who told you that? You you can make this comparison. Only it will not compare the contents of the strings, but the values of the two pointers (and they, of course, will not be equal). And what exactly did you want to compare-strings or pointers - this is what you need to ask. The compiler will not think for you, it just does what you told it to do.

 2
Author: AnT, 2018-12-29 23:59:19

You need std::strcmp.

But in general, if this is C++ (judging by the tag), then it may make sense to get rid of character arrays and switch to std::string.


As you noticed in the next answer, in scanf("%s", &kodG);, the character & is superfluous. Although it creates undefined behavior here, in practice it should not affect the operation of the program, in theory.

 4
Author: HolyBlackCat, 2018-12-29 22:35:07