Compare equality of char[] in C

大兔子大兔子 提交于 2019-11-29 09:36:41
char charTime[] = "TIME"; char buf[] = "SOMETHINGELSE";

C++ and C (remove std:: for C):

bool equal = (std::strcmp(charTime, buf) == 0);

But the true C++ way:

std::string charTime = "TIME", buf = "SOMETHINGELSE";
bool equal = (charTime == buf);

Using == does not work because it tries to compare the addresses of the first character of each array (obviously, they do not equal). It won't compare the content of both arrays.

In c you could use the strcmp function from string.h, it returns 0 if they are equal

#include <string.h>

if( !strcmp( charTime, buf ))

In an expression using == the names of char arrays decay into char* pointing to the start of their respective arrays. The comparison is then perform in terms of the values of the pointers themselves and not the actual contents of the arrays.

== will only return true for two pointers pointing to the same location and false otherwise, even if they are pointing to two arrays with identical contents.

What you need is the standard library function strcmp. This expression evaluates as true if the arrays contain the same contents (up to the terminating null character which must be present in both arrays fro strcmp to work safely).

strcmp(charTime, buf) == 0

Check them in a for loop. Get the ASCII numbers for each char once they change they're not equal.

You are checking the identity charTime and buf. To check the equality, loop over each character in one array and compare them with the related character in the other array.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!