是/否程序在 C++ 中使用 while 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40156859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Yes/No program using while loop in C++
提问by Horsey Potato
I'm trying to make a program that asks the user whether they would like to continue to the next calculation. For some reasons whenever I enter y or Y, the program ends. However, if I use only one condition inside the if statement(without '||'sign), the code works fine. I just want to make sure that the user can enter both upper and lower case.
我正在尝试制作一个程序,询问用户是否愿意继续进行下一次计算。由于某些原因,每当我输入 y 或 Y 时,程序就会结束。但是,如果我在 if 语句中只使用一个条件(没有 '||' 符号),则代码工作正常。我只想确保用户可以输入大写和小写。
What's wrong with the code? Is there a better way to do this?
代码有什么问题?有一个更好的方法吗?
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;
}
回答by Treycos
The return
statement ends a function, in this case, this is the main, so it ends your program, whatever value you're returning.
If you only want to get out of your loop you have two solutions:
Use a boolean:
该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;
}
Use break
to exit your loop:
使用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;
}
But both these solution will consider any character entered exept N/n as "continue", if you want to avoid this:
但是,如果您想避免这种情况,这两种解决方案都会将除 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;
}
回答by Christian Dean
For some reasons whenever I enter y or Y, the program ends
由于某些原因,每当我输入 y 或 Y 时,程序就会结束
The return
statement is used to return control(and sometimes an optional value), to a functions caller. When return is used inside the called function, the function is terminated. From cppreference.com:
该return
语句用于将控制(有时是可选值)返回给函数调用者。当在被调用函数内使用 return 时,函数将终止。来自 cppreference.com:
[return] terminates [the] current function and returns [a] specified value to the caller function.
[return]终止 [the] 当前函数并将 [a] 指定值返回给调用者函数。
(emphasis mine)
(强调我的)
You may be under the impression that the statement return true
inside your while-loop is returning the Boolean value of true to your while condition. It is not.
您可能认为return true
while 循环中的语句将布尔值 true 返回到您的 while 条件。它不是。
If your end goal is to create a yes/no style program that ends when the user enters "No/no", then you can to make use of the continue
and break
statements, or use a do/while
loop.
如果您的最终目标是创建一个是/否风格的程序,当用户输入“否/否”时结束,那么您可以使用continue
andbreak
语句,或使用do/while
循环。
Using continue
and break
使用continue
和break
The continue
statement is used to immediately skip to the next iteration of a loop, for or while, terminating the current iteration. From cppreference.com:
该continue
语句用于立即跳到循环的下一次迭代,for 或 while,终止当前迭代。来自 cppreference.com:
Causes the remaining portion of the enclosing for, range-for, while or do-while loop body to be skipped. Used when it is otherwise awkward to ignore the remaining portion of the loop using conditional statements.
使封闭的 for、range-for、while 或 do-while 循环体的剩余部分被跳过。当使用条件语句忽略循环的剩余部分很尴尬时使用。
(emphasis mine)
(强调我的)
The break
statement is somewhat similar to continue
, but instead of breaking the current iteration and skipping to the next one, it immediately breaks the entire program out of the while loop returning control to the outer-scope. From cppreference.com:
该break
语句有点类似于continue
,但它不是中断当前迭代并跳到下一个迭代,而是立即将整个程序从 while 循环中中断,将控制权返回到外部作用域。来自 cppreference.com:
Causes the enclosing for, range-for, while or do-while loop or switch statement to terminate.Used when it is otherwise awkward to terminate the loop using the condition expression and conditional statements.
导致封闭的 for、range-for、while 或 do-while 循环或 switch 语句终止。当使用条件表达式和条件语句终止循环很尴尬时使用。
(emphasis mine)
(强调我的)
After examining the information above, you can modify your program to make use of continue
and break
, instead of return
:
检查上述信息后,您可以修改您的程序以使用continue
and 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;
}
Using a do/while
loop
使用do/while
循环
While the method above would work, I recommend using my second option-- a do/while
loop. The do/while
has the advantage o being shorter, and not having to make use of any kind of major control flow. From cppreference:
虽然上述方法可行,但我建议使用我的第二个选项——do/while
循环。在do/while
具有优势o为短,不必使用任何一种主要的控制流的。来自 cppreference:
Executes a statement repeatedly, until the value of expression becomes false. The test takes place after each iteration.
重复执行一条语句,直到表达式的值变为假。测试在每次迭代后进行。
If needed you could even add error checking to validate a users input:
如果需要,您甚至可以添加错误检查来验证用户输入:
#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;
}
Output
输出
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
References and Resources
参考资料和资源
回答by Horsey Potato
I just wrote some code and it works like a charm using "goto". The code also included data validation as well. Many thanks to @Treycos.
我刚刚写了一些代码,它使用“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;
}
Output:
输出:
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)
For uppercase n:
对于大写 n:
2
Would you like to perform other calculation?(Y/N)
N
Process returned 0 (0x0)