[英]Trying to find out why my code keeps infinite looping
I am very new to programming so pardon my lack of knowledge.我对编程很陌生,所以请原谅我缺乏知识。 I am trying to create a simple menu in which I am going to execute a few problems by pressing 1,2,3 etc. but my code keeps looping over and over again and I can't understand why.我正在尝试创建一个简单的菜单,我将在其中按 1、2、3 等执行一些问题,但我的代码一遍又一遍地循环,我不明白为什么。
int main()
{
int choice;
do
{
cout << "\t|--------------------------- Menu ---------------------------|" << endl;
cout << "1.|- Добавяне на телефонни номера -|" << endl;
cout << "2.|- Извеждане на всички телефонни абонати на екрана -|" << endl;
cout << "3.|- Месечно потребление -|" << endl;
cout << "4.|- Изчисление на месечна такса -|" << endl;
cout << "5.|- Справки за абонатите с под меню -|" << endl;
cout << "6.|- Край на програмата -|" << endl;
switch(choice)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
cout << "|- Благодаря ви -|" << endl;
return 0;
}
}
while(choice != 6);
}
You need to use cin
in your code in order to change what choice
is every time that you go through the loop.您需要在代码中使用cin
以便在每次循环时更改choice
。 Also it is a good idea to handle invalid user inputs.处理无效的用户输入也是一个好主意。 This is done by (!(cin >> choice))
until input will return true
.这是由(!(cin >> choice))
直到输入将返回true
。 While this is the case you want to cin.clear()
and cin.ignore()
to reset the state of the stream so that you can keep asking the user for a correct input.在这种情况下,您希望cin.clear()
和cin.ignore()
重置流的状态,以便您可以继续要求用户提供正确的输入。
#include<iostream>
using namespace std;
int main()
{
// it is a good idea to initialize the variable when you create it
int choice = 0;
do
{
cout << "\t|--------------------------- Menu ---------------------------|" << endl;
cout << "1.|- Добавяне на телефонни номера -|" << endl;
cout << "2.|- Извеждане на всички телефонни абонати на екрана -|" << endl;
cout << "3.|- Месечно потребление -|" << endl;
cout << "4.|- Изчисление на месечна такса -|" << endl;
cout << "5.|- Справки за абонатите с под меню -|" << endl;
cout << "6.|- Край на програмата -|" << endl;
// this loop will handle incorrect inputs from the user
// for example entering a char, when the stream is expecting an int
while (!(cin >> choice))
{
cin.clear();
cin.ignore();
cout << "Please enter a valid choice: ";
cin >> choice;
}
switch (choice)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
cout << "|- Благодаря ви -|" << endl;
return 0;
}
} while (choice != 6);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.