我在检查变量值是否匹配时遇到问题。我正在使用 if 语句来检查 health 变量是否具有良好的值,但下面的代码给出了错误。
#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 语句来检查健康状况是否 == 优秀时,它都不起作用。我什至尝试过使用双引号和单引号。
最佳答案
在 C++ 中使用类似 strcmp
的函数来比较字符串。
if(strcmp(health,"excellent")==0)
{
...
}
在 C++ 中,您无法直接将创建为 char
数组的字符串与 ==
进行比较,也无法对字符串使用 double-qoutes
C++ 。单引号用于字符。
您可以将字符串创建为 std::string
类的对象,然后使用重载运算符来比较 C++ 中的字符串。阅读this
关于c++ - 如何与字符串文字进行字符串比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23191475/