这里我有一个异常处理程序,其中我使用了&&运营商比较城市名称, 我有问题,我有&&运营商如果条件但我们知道&&只有当这个程序中的所有值都为真时才执行,即使我们输入一个值,这个程序也能正确执行。
为什么&&的含义操作员更改此程序?
#include<iostream>
#include<typeinfo>
#include<string>
#include<cstring>
using namespace std;
int main() {
int i, n, age; //variable declaration
double income;
char city[20];
cout<<"\n Enter your age:";
cin>>age;
try {
if (age < 18 || age > 55)
throw runtime_error("\n Age is not in the range of 18-55");
} catch(const exception& e) { //creation of exception object 'e'
cout<<"EXCEPTION:"<<e.what()<<'\n'; //what()- member funciton of type id
}
cout<<"\n Enter your income:";
cin>>income;
try {
if(income<50000||income>100000)
throw runtime_error("\n Income is not in the range of 50000-100000");
} catch(const exception& e)// creation of exception object 'e'
{
cout<<"EXCEPTION:"<<e.what()<<'\n';
}
cout<<"\n In which city do you live?";
cin>>city;
try {
if(strcmp(city, "Pune")
&& strcmp(city, "Banglore")
&& strcmp(city,"Chennai")
&& strcmp(city, "Mumbai"))
throw runtime_error("\ncity is not any of these:- Pune/Mumbai/Banglore/Chennai");
} catch(const exception& e)// creation of exception object 'e'
{
cout<<" EXCEPTION:"<<e.what()<<'\n';
}
cout<<"\n Information of person is as follows:";// displpaying all the information accepted
cout<<"\n Age:"<<age;
cout<<"\n Income:"<<income;
cout<<"\n City:"<<city;
return 0;
}
答案 0 :(得分:1)
你知道std :: strcmp(p1,p2)返回整数值,含义如下:
0两个字符串的内容相等
&GT; 0不匹配的第一个字符在p1中的值大于在p2中的值
因此,例如,如果用户输入&#34;莫斯科&#34;比我们得到的: (1&amp;&amp; -1&amp;&amp; -1&amp;&amp; 1)但它的意思是(真&amp;&amp;真&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;真)和异常将是抛出
相反,您应该只检查相等性,所以只需将代码更改为: ...
if((strcmp(city, "Pune") != 0) && (strcmp(city, "Banglore") != 0) && (strcmp(city,"Chennai") != 0) && (strcmp(city, "Mumbai")!=0))
...