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

Yes/No program using while loop in C++

本文关键字:程序 循环 while c++      更新时间:2023-10-16

我正在尝试编写一个程序,询问用户是否要继续进行下一个计算。由于某些原因,每当我输入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;
}

return语句结束了一个函数,在本例中,这是main,所以它结束了你的程序,无论你返回的是什么值
如果你只想跳出循环,你有两个解决方案:
使用布尔值:

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之外的任何字符视为"continue":

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;
}

由于某些原因,每当我输入y或y时,程序都会结束

return语句用于将控制权(有时是可选值)返回给函数调用者。当在被调用的函数中使用return时,函数终止。从cppreference.com:

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

<子>(强调我的)

您可能有这样的印象:while循环中的语句return true将布尔值true返回给while条件。它不是。


如果你的最终目标是创建一个yes/no风格的程序,当用户输入"no/no"时结束,那么你可以使用continuebreak语句,或者使用do/while循环。


使用continuebreak

continue语句用于立即跳到循环的下一个迭代,for或while,终止当前迭代。从cppreference.com:

导致跳过for、range-for、while或do-while循环体的其余部分。在使用条件语句难以忽略循环的其余部分时使用。

<子>(强调我的)

break语句有点类似于continue,但它没有中断当前迭代并跳转到下一个迭代,而是立即将整个程序从while循环中中断,将控制返回到外部作用域。从cppreference.com:

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

<子>(强调我的)

在检查了上面的信息之后,您可以修改您的程序以使用continuebreak,而不是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循环。do/while的优点是较短,并且不必使用任何类型的主要控制流。从cppreference:

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

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

#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;
}

输出
Would you like to perform other calculations?(Y/N)
 y
Would you like to perform other calculations?(Y/N)
 Y
Would you like to perform other calculations?(Y/N)
 n

参考资料和资源

  • cppreference.com
  • cplusplus.com

我刚刚写了一些代码,它像一个魅力使用"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)