C++ 带字符串的简单 if 条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10373017/
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
Simple if condition with strings
提问by user1341970
Possible Duplicate:
How do I properly compare strings in C?
可能的重复:
如何正确比较 C 中的字符串?
#include <iostream>
using namespace std;
int main(){
char name[100];
cout<<"Enter: ";
cin>>name;
if(name == "hello"){
cout<<"Yes it works!";
}
return 0;
}
Why when I entered hello in the prompt i didnt got "Yes it works!" message?
为什么当我在提示中输入 hello 时我没有得到“是的,它有效!” 信息?
回答by Luchian Grigore
You need to use strcmp
to test for equality.
您需要使用strcmp
来测试是否相等。
name
is an array, not a std::string
, and hello
is a string literal, i.e. a const char*
. You're comparing pointers, not strings.
name
是一个数组,而不是 a std::string
,并且hello
是一个字符串文字,即 a const char*
。您正在比较指针,而不是字符串。
回答by Pedro
Try this:
尝试这个:
#include <string.h>
#include <iostream>
using namespace std;
int main(){
char name[100];
cout<<"Enter: ";
cin>>name;
if(strcmp(name, "hello") == 0) {
cout << "Yes it works!";
}
return 0;
}
回答by Bo Persson
If you use std::string
instead of a char array, it will work:
如果您使用std::string
而不是字符数组,它将起作用:
#include <iostream>
#include <string>
using namespace std;
int main(){
? ? string name;
? ? cout<<"Enter: ";
? ? cin>>name;
? ? if(name == "hello"){
? ? ? ? cout<<"Yes it works!";
? ? }
? ? return 0;
}
回答by HostileFork says dont trust SE
There are low-level strings ("C strings") which do not have the high-level behaviors you have probably come to expect from other languages. When you type in a string literal (in "quotes") you are creating one of those types of strings:
有一些低级字符串(“C 字符串”)没有您可能期望从其他语言获得的高级行为。当您输入字符串文字(在“引号”中)时,您正在创建以下类型的字符串之一:
http://en.wikipedia.org/wiki/C_string_handling
http://en.wikipedia.org/wiki/C_string_handling
In C++, one of the first things people do is pass that low-level string to the constructor of std::string
to create an instance of a class that has more of the conveniences in interface that you would be used to.
在 C++ 中,人们做的第一件事就是将低级字符串传递给 的构造函数,std::string
以创建一个类的实例,该实例在接口中具有您习惯的更多便利。
http://www.cplusplus.com/reference/string/string/
http://www.cplusplus.com/reference/string/string/
Because C++ is layered over a very C-like foundation, it's valuable to understand how C-style strings work. At the same time, a professional/idiomatic C++ program should not use functions like strcmp
. For an interesting study into the differences between C style programming and C++ style programming, check this out:
因为 C++ 是在一个非常类似于 C 的基础上分层的,所以了解 C 风格的字符串如何工作是很有价值的。同时,专业/惯用的 C++ 程序不应该使用strcmp
. 要对 C 风格编程和 C++ 风格编程之间的差异进行有趣的研究,请查看:
Learning Standard C++ As A New Language (PDF)by Bjarne
学习标准 C++ 作为一种新语言 (PDF)by Bjarne