我在檢查變量值是否匹配時遇到問題。我正在使用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語句來檢查健康是否==好,它不起作用。我甚至嘗試使用雙引號和單引號。
你需要'strcmp'來自'string'庫... google it – GoldRoger
你的代碼中的問題是'excellent'。單引號用於字符文字,而雙引號用於字符串。 – cbel
請注意,單引號是字符文字,雙引號字符串文字, –