我有一个关于研讨会注册的项目。
我设法完成了结构化课程,也列出了研讨会的内容。目前,我对注册有一个问题。问题是这样的:用户会输入他想要注册的研讨会。一旦用户注册了研讨会,它将导致研讨会要么成功注册(如果有插槽),要么失败(如果所有插槽都被占用)。
我所拥有的代码能够打印出结果,但是它显示了它循环通过的所有结果。有什么方法可以让我打印用户输入的特定研讨会的结果吗?
下面是我的密码。我知道我做了一个for循环。但我不太确定如何才能在不循环的情况下显示单个结果。
结构:
struct Seminar
{
string Title;
int Capacity;
};
Seminar theSeminar[4];职能:
void registerSem(string sem){
for (int i = 0; i < 4; i++)
{
if( theSeminar[i].Title == sem){
if (theSeminar[i].Capacity > 0)
{
theSeminar[i].Capacity = theSeminar[i].Capacity - 1;
cout << "Successful registered!" << endl;
}
else{
cout << "Unsuccessful registration" << endl;
}
}
else{
cout << "Not Found" << endl;
}
}
}发布于 2017-08-23 19:24:20
你需要把打印移出循环。您可以通过添加一个found变量来做到这一点,然后您可以检查该变量:
void registerSem(string sem){
bool found = false;
for (int i = 0; i < 4; i++)
{
if( theSeminar[i].Title == sem){
found = true;
if (theSeminar[i].Capacity > 0)
{
theSeminar[i].Capacity = theSeminar[i].Capacity - 1;
cout << "Successful registered!" << endl;
}
else{
cout << "Unsuccessful registration" << endl;
}
break;
}
}
if (!found)
{
cout << "Not Found" << endl;
}
}您还可以通过从整个函数返回代码来简化代码,一旦发现研讨会:
void registerSem(string sem) {
for (int i = 0; i < 4; i++) {
if (theSeminar[i].Title == sem) {
if (theSeminar[i].Capacity > 0) {
theSeminar[i].Capacity -= 1;
cout << "Successfully registered!\n";
}
else {
cout << "Unsuccessful registration\n";
}
return;
}
}
cout << "Not found\n";
}或者,你也可以把寻找合适的研讨会并用它做些什么的问题分开:
void registerSem(string sem) {
int found_at = -1;
for (int i = 0; i < 4; i++) {
if (theSeminar[i].Title == sem) {
found_at = i;
break;
}
}
if (found_at == -1) {
cout << "Not found\n";
return;
}
if (theSeminar[found_at].Capacity <= 0) {
cout << "Unsuccessful registration\n";
return;
}
theSeminar[found_at].Capacity -= 1;
cout << "Successfully registered!\n";
}https://stackoverflow.com/questions/45847535
复制相似问题