0

Possible Duplicate:
How do I properly compare strings in 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?

4

4 回答 4

9

您需要用于strcmp测试是否相等。

name是一个数组,而不是 a std::string,并且hello是一个字符串文字,即 a const char*。您正在比较指针,而不是字符串。

于 2012-04-29T14:41:57.717 回答
4

尝试这个:

#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; 
} 
于 2012-04-29T14:44:48.493 回答
3

如果您使用std::string而不是 char 数组,它将起作用:

#include <iostream>
#include <string>
using namespace std;

int main(){

    string name;
    cout<<"Enter: ";
    cin>>name;
    if(name == "hello"){
        cout<<"Yes it works!";
    }

    return 0;
}
于 2012-04-29T14:50:05.663 回答
1

有些低级字符串(“C 字符串”)不具备您可能期望从其他语言获得的高级行为。当您输入字符串文字(在“引号”中)时,您正在创建这些类型的字符串之一:

http://en.wikipedia.org/wiki/C_string_handling

在 C++ 中,人们做的第一件事就是将该低级字符串传递给 的构造函数,std::string以创建一个类的实例,该实例在接口中具有您将习惯使用的更多便利。

http://www.cplusplus.com/reference/string/string/

因为 C++ 是在一个非常类似于 C 的基础上分层的,所以了解 C 风格的字符串是如何工作的很有价值。同时,专业/惯用的 C++ 程序不应使用strcmp. 要对 C 风格编程和 C++ 风格编程之间的差异进行有趣的研究,请查看以下内容:

学习标准 C++ 作为一种新语言 (PDF) by Bjarne

于 2012-04-29T14:49:07.573 回答