是/否在C ++中使用while循环的程序

时间:2016-10-20 14:09:59

标签: c++

我试图制作一个程序,询问用户是否愿意继续下一次计算。出于某些原因,每当我输入y或Y时,程序结束。但是,如果我在if语句中只使用一个条件(没有' ||'符号),则代码可以正常工作。我只是想确保用户可以输入大写和小写。

代码有什么问题?有更好的方法吗?

int main()
{
    char choice;
    while(true)
    {
        cout<<"Would you like to perform other calculation?(Y/N)"<<endl;
        cin >> choice;
        if(choice == 'Y'|| choice =='y'){
        return true;
        }else if(choice =='N'||choice =='n'){
        return false;
        }
    }
return 0;
}

3 个答案:

答案 0 :(得分:2)

return语句结束一个函数,在这种情况下,这是主函数,因此无论你返回什么值,它都会结束你的程序。
如果你只想摆脱循环,你有两个解决方案:
使用布尔值:

int main()
{
    char choice;
    bool run = true; //@stefaanv
    while(run)
    {
        // Make your calculation
        cout<<"Would you like to perform other calculation?(Y/N)"<<endl;
        cin >> choice;
        if(choice =='N'||choice =='n'){
            run = false;
        }
    }
return 0;
}

使用break退出循环:

int main()
{
    char choice;
    while(true)
    {
        // Make your calculation
        cout<<"Would you like to perform other calculation?(Y/N)"<<endl;
        cin >> choice;
        if(choice =='N'||choice =='n'){
            break;
        }
    }
return 0;
}

但是如果你想避免这种情况,这两个解决方案都会认为输入的任何字符都是N / n,如果你想避免这种情况:

int main()
{
    char choice;
    bool run = true;
    while(run)
    {
        // Make your calculation
        do{
            cout<<"Would you like to perform other calculation?(Y/N)"<<endl;
            cin >> choice;
            choice = tolower(choice);//Put your letter to its lower case
        }while (choice != 'n' && choice != 'y')
        if(choice =='n'){
            run = false;
        }
    }
return 0;
}

答案 1 :(得分:1)

  

出于某些原因,每当我输入y或Y时,程序结束

return语句用于将控制(有时是可选值)返回给函数调用者。在被调用函数内部使用return时,函数终止。来自cppreference.com:

  

[return] 终止[当前]函数并将[a]指定值返回给调用函数

(强调我的)

您可能会认为,while循环中的语句return true会将布尔值true返回到while条件。事实并非如此。

如果您的最终目标是创建一个yes / no样式程序,该程序在用户输入&#34; No / no&#34;时结束,那么您可以使用continue和{{1 }}语句,或使用break循环。

使用do/whilecontinue

break语句用于立即跳转到循环的下一次迭代,for或while,终止当前迭代。来自cppreference.com:

  

导致包围for,range-for,while或do-while循环体的剩余部分被跳过。   在使用条件语句忽略循环的剩余部分时很难使用。

(强调我的)

continue语句有点类似于break,但它不会打破当前迭代并跳到下一个迭代,而是立即将整个程序从while循环中断开,将控制权返回到外部-范围。来自cppreference.com:

  

导致封闭for,range-for,while或do-while循环或switch语句终止。   在使用条件表达式和条件语句终止循环时很难使用。

(强调我的)

在检查了上述信息后,您可以修改您的计划以使用continuecontinue,而不是break

return

使用#include <iostream> using namespace std; // This is for demonstration purposes ONLY // never use this statement in your actual program. prefix cout and // cin with std:: int main() { char choice; while(true) { cout<<"Would you like to perform other calculations?(Y/N)"<<endl; cin >> choice; if(choice == 'Y'|| choice =='y'){ continue; // instead of returning, skip to the next iteration // and ask again }else if(choice =='N'||choice =='n'){ break; // return could be used here to break the while loop and // terminate the program. But be explicit and use a statement specifically // made for breaking out of loops } } return 0; } 循环

虽然上面的方法可行,但我建议使用我的第二个选项 - do/while循环。 do/while具有更短的优点,而不必使用任何类型的主要控制流程。来自cppreference:

  

重复执行一个语句,直到表达式的值变为false。测试在每次迭代后进行。

如果需要,您甚至可以添加错误检查以验证用户输入:

do/while

输出

#include <iostream>
using namespace std; // This is for demonstration purposes ONLY
// never use this statement in your actual program. prefix cout and
// cin with std::

int main()
{
    char choice;
    do { // do everything in the do block while...

        cout <<"Would you like to perform other calculations?(Y/N)"<< endl;

        cin >> choice;

        if (choice != 'Y' and choice != 'y' and choice != 'N' and choice != 'n') // if needed add input 
            cout << choice << " is not a valid option. Try agian" << endl; // validation

    } while (choice !='N' && choice !='n'); // the user input does not equal 'N'andr 'n'

return 0;
}

参考资料和资源

答案 2 :(得分:0)

我刚写了一些代码,它就像使用“goto”的魅力一样。 该代码还包括数据验证。非常感谢@Treycos。

int main()
{
char choice ='Y';
bool valid = true;
//some calculation
        here:
        int x =1+1;
        cout<<x<<endl;
    while(valid){
            cout<<"Would you like to perform other calculation?(Y/N)"<<endl;
            cin >> choice;
            if(choice =='N' || choice =='n'){
                break;
        }
            if(choice =='Y'||choice =='y'){
                goto here;
        }
         else if(choice != 'N'&& choice != 'n'&&choice != 'Y'&&choice != 'y'){
                cout<<"Invalid input."<<endl;
                valid = true;
        }
}
return 0;
}

输出:

2
Would you like to perform other calculation?(Y/N)
y
2
Would you like to perform other calculation?(Y/N)
Y
2
Would you like to perform other calculation?(Y/N)
$
Invalid input.
Would you like to perform other calculation?(Y/N)
n

Process returned 0 (0x0)

对于大写n:

2
Would you like to perform other calculation?(Y/N)
N

Process returned 0 (0x0)