用C比较的char []平等 [英] Compare equality of char[] in C

查看:117
本文介绍了用C比较的char []平等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个变量:

 字符charTime [] =TIME;
烧焦BUF [] =SOMETHINGELSE;

我要检查,如果这两个都是平等的......使用 charTime == BUF 不起作用。

我应该怎么用了,有人可以解释为什么使用 == 不起作用?

请问这个动作是C和C ++不同?


解决方案

 字符charTime [] =TIME;烧焦BUF [] =SOMETHINGELSE;

C ++ C (删除的std :: 为C):

 布尔等于=(的std :: STRCMP(charTime,BUF)== 0);

但是,真正的C ++方式:

 的std ::字符串charTime =TIME,BUF =SOMETHINGELSE;
布尔等于=(charTime == BUF);

使用 == 不起作用,因为它试图地址比较每个阵列(显然​​,他们这样做不等于)的第一个字符。它不会比较两个阵列的内容。

I have two variables:

char charTime[] = "TIME";
char buf[] = "SOMETHINGELSE";

I want to check if these two are equal... using charTime == buf doesn't work.

What should I use, and can someone explain why using == doesn't work?

Would this action be different in C and C++?

解决方案

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.

这篇关于用C比较的char []平等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆