【发布时间】:2020-12-01 06:54:53
【问题描述】:
我正在尝试制作日志程序,但遇到了这个问题。即使有 break 语句,它也总是循环。
这是我在 while 循环中使用 break 语句的部分,但它一直在无休止地循环。
void userPrompt(){
while(true){
cout << "[1] Log in\n";
cout << "[2] Log out\n";
cout << "[3] View Log Book\n";
cout << "[0] Exit\n";
cout << "Choice: ";
cin >> choice;
cout << endl;
switch(choice){
case 1:
logIn();
break;
case 2:
logOut();
break;
case 3:
viewRecords();
break;
case 4:
break;
default:
cout<<"Invalid Choice. PLease try again\n";
break;
}
}
}
这是完整的代码
#include<string>
using namespace std;
struct node{
string name;
int timeIn, timeOut;
node* nextNode;
};
class LogBook{
private:
node* head = NULL;
node* tail = NULL;
int choice;
public:
void userPrompt(){
while(true){
cout << "[1] Log in\n";
cout << "[2] Log out\n";
cout << "[3] View Log Book\n";
cout << "[0] Exit\n";
cout << "Choice: ";
cin >> choice;
cout << endl;
switch(choice){
case 1:
logIn();
break;
case 2:
logOut();
break;
case 3:
viewRecords();
break;
case 4:
break;
default:
cout<<"Invalid Choice. PLease try again\n";
break;
}
}
}
void logIn(){
string name;
int time;
node* temp = new node();
cout << "Enter your name: ";
cin >> name;
cout << "Time in: ";
cin >> time;
cout << endl;
temp->name = name;
temp->timeIn = time;
temp->nextNode = NULL;
if(head == NULL){
head = temp;
tail = temp;
}
else{
tail->nextNode = temp;
tail = tail->nextNode;
}
}
void logOut(){
string name;
int time;
node* temp;
temp = head;
cout << "Enter Name: ";
cin >> name;
while(temp != NULL){
if(temp->name == name){
cout << "Time out: ";
cin >> time;
temp->timeOut = time;
}
else
cout << "Name not found\n";
break;
}
}
void viewRecords(){
node* temp;
temp = head;
while(temp != NULL){
cout << "\nLog records:\n";
cout << "Name: " << temp->name << endl;
cout << "Time in: " << temp->timeIn << endl;
cout << "Time out: " << temp->timeOut << endl;
temp = temp->nextNode;
}
}
};
int main(){
LogBook user1;
user1.userPrompt();
return 0;
}`
【问题讨论】:
-
我看到的唯一
break会影响switch,循环的break在哪里? -
开关内部的
break,仅从开关盒中断开。你也需要再休息一会儿。