相关疑难解决方法(0)

C++,'if'表达式中的变量声明

这里发生了什么?

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)?

c++ if-statement compilation variable-declaration

104
推荐指数
5
解决办法
5万
查看次数

多个if语句cpp

我不喜欢有很多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)

c++ if-statement

-1
推荐指数
1
解决办法
118
查看次数

我用这个字符串得到了一个无限的 while 循环

所以我在这里得到了这部分代码:

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)

问题是即使我给他一个正确的答案,比如“华硕”,它仍然给我错误信息:“你的输入错误”我该怎么办?

c++ while-loop

-2
推荐指数
1
解决办法
88
查看次数