2014-04-21 236 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

相關問題