这里发生了什么?
if(int a = Func1())
{
// Works.
}
if((int a = Func1()))
{
// Fails to compile.
}
if((int a = Func1())
&& (int b = Func2()))
)
{
// Do stuff with a and b.
// This is what I'd really like to be able to do.
}
Run Code Online (Sandbox Code Playgroud)
2003标准中的6.4.3节阐述了在选择语句条件中声明的变量如何具有延伸到由条件控制的子语句末尾的范围.但是我没有看到它在什么地方说不能在括号内加上括号,也没有说明每种条件只有一个声明.
即使在需要条件中只有一个声明的情况下,这种限制也很烦人.考虑一下.
bool a = false, b = true;
if(bool x = a || b)
{
}
Run Code Online (Sandbox Code Playgroud)
如果我想在x设置为false的情况下输入'if"-body范围,则声明需要括号(因为赋值运算符的优先级低于逻辑OR),但由于括号不能使用,因此需要声明外部x身体,将声明泄露到比预期更大的范围.显然这个例子是微不足道的,但更现实的情况是a和b是函数返回需要测试的值
那么我想要做的是不符合标准,还是我的编译器只是破坏了我的球(VS2008)?
我不喜欢有很多if语句.无论如何,有一个If语句允许int等于多个数字然后执行语句,如果输入这些数字中的任何一个?
#include <iostream>
using namespace std;
int main()
{
int year;
cin>>year;
//Rat
if (year==2008)
cout<<"The year "<< year <<" is the year of the Rat";
if (year==1996)
cout<<"The year "<< year <<" is the year of the Rat";
if (year==1984)
cout<<"The year "<< year <<" is the year of the Rat";
if (year==1972)
cout<<"The year "<< year <<" is the year of the Rat";
//Error message
if (year<1964)
cout<<"Please enter a valid number.";
if (year>2018)
cout<<"Please enter a valid …Run Code Online (Sandbox Code Playgroud) 所以我在这里得到了这部分代码:
string stringparam;
string stringparam1;
double d;
unsigned x;
cout << "Welcome" << endl;
cout << "Choose one (ASUS, MSI, Gigabyte, ASrock)" << endl;
cin >> stringparam;
while (stringparam != "ASUS" || "MSI" || "Gigabyte" || "ASrock")
{
cout << "you gave bad input \n" << endl;
cout << "Choose one (ASUS, MSI, Gigabyte, ASrock)" << endl;
cin >> stringparam;
}
Run Code Online (Sandbox Code Playgroud)
问题是即使我给他一个正确的答案,比如“华硕”,它仍然给我错误信息:“你的输入错误”我该怎么办?