我在检查变量值是否匹配时遇到问题。我正在使用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
请注意,单引号是字符文字,双引号字符串文字, –