2014-04-21 238 views
0

我在检查变量值是否匹配时遇到问题。我正在使用if语句来检查健康变量是否具有优异的值,但下面的代码会给出错误。如何与字符串文字进行字符串比较?

#include <iostream> 

using namespace std; 

class person { 
private: 
    char health[20], city[20], gender[20]; 
    int age; 
public: 
    void getdata(); 
    void dispdata(); 
}; 

void person::getdata() 
{ 
    cout <<" Enter the person's health"; 
    cin >> health; 
    cout << "Enter your age"; 
    cin >> age; 
    cout << " Do you live in city"; 
    cin >> city; 
    cout << "Gender: male or female"; 
    cin >> gender; 
} 

void person::dispdata() 
{ 
    if(health == 'excellent') { 
     cout << "The person can be insured\n"; 
     cout << "his premium is $4 per thousand and his policy amount cannot exceed Rs. 200,000."; 
    } else { 
     cout << "Error"; 
    } 
} 
int main() 
{ 
    person s1; 
    s1.getdata(); 
    s1.dispdata(); 
    return 0; 
} 

无论何时我使用if语句来检查健康是否==好,它不起作用。我甚至尝试使用双引号和单引号。

+0

你需要'strcmp'来自'string'库... google it – GoldRoger

+0

你的代码中的问题是'excellent'。单引号用于字符文字,而双引号用于字符串。 – cbel

+0

请注意,单引号是字符文字,双引号字符串文字, –

回答

0

使用strcmp类似函数来比较C++中的字符串。

if(strcmp(health,"excellent")==0) 
{ 
... 
} 

在C++中你不能比较的是作为char阵列直接创造了==字符串,还可以使用double-qoutes字符串C++。单引号是用于字符。
您可以创建字符串作为std::string类的oblect,然后使用重载运算符来比较C++中的字符串。阅读this

+0

,一个工作正常。但是如果年龄在24岁到36岁之间,你能告诉我如何检查那个领域吗? – rahulkapoor99

+0

@ rahulkapoor99你想测试那个条件吗?年龄是'int'的,因此你可以直接把一个条件作为24 <=年龄&&年龄<= 36的测试吗?有什么问题? – LearningC

+0

ohh..sorry我只是搞乱了格式。谢谢你的方式。 – rahulkapoor99

相关问题