如何简单地比较 C++ 中的字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15801840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I simply compare characters in C++?
提问by Dmitriy Potemkin
I have the following code:
我有以下代码:
#include <iostream>
using namespace std;
int main()
{
char fg;
cin>>fg;
char x[20];
x[0]='0';
if(fg=x[0])
{
cout<<"It's true!"<<endl;
return true;
}
cout<<"It's false!"<<endl;
return false;
}
No matter what input I give, true
is always returned. Is my syntax off? Any help would be appreciated.
无论我给出什么输入,true
总是返回。我的语法关闭了吗?任何帮助,将不胜感激。
回答by dasblinkenlight
In C++ you use ==
for comparison. The =
is an assignment. It can be used in the condition of an if
statement, but it's going to evaluate to true
unless the character is '\0'
(not '0'
, as it is in your case):
在 C++ 中,您==
用于比较。这=
是一个任务。它可以在if
语句的条件中使用,但true
除非字符是'\0'
(不是'0'
,就像你的情况一样),否则它将被评估为:
if(fg == x[0])
{
...
}
回答by Rijesh4
Within if statement use ==
. For Eg:
在 if 语句中使用==
。例如:
if (fg == x[0]) {
//...........
}
==
compares, but =
makes fg
equal to x[0]
, and that's why you get true every time.
==
相比较,但=
品牌fg
等于x[0]
,这就是为什么你每次都获得正确的。