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
2 answers
-
Using the
&
operator with the%s
format inscanf
is almost always an errorscanf("%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.
-
Using an array as small as 5 for user input via
scanf("%s"
is a serious buffer overflow claim. all the consequences. Do at leastscanf("%4s", kodG);
-
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)
-
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.
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.