コード構造の可能性のある分割の1つが、より手続き的な方法(これを「オブジェクト指向」と呼ぶことはありません)にします。 同様の方法で、メニュー処理コードを各オプションなどの別々の機能に分割することができます。
これはマルチユーザーアプリケーションの場合、単純なtrue/false完全資格情報ではなく、 name, code
を含む構造を持つようなユーザー認証を受けています(後で必要がない場合は、パスワードを長い間メモリに保持しないように、認証後にパスワードを捨てる可能性があります)。
// returns true if user wants to exit
// sets authenticated to true when the Drew user is detected
bool AuthenticateUser(bool & authenticated) {
cout << "Enter your username >" << flush;
...
if (name == "Drew" && ...) {
authenticated = true;
cout << "Access granted. Welcome, " << name << "." << endl;
cout << "Welcome to Database of Drew" << endl;
return false;
}
cout << "Access denied..." << " Try again? (Y/N) >" << flush;
...
return (ask == "N" || ask == "n"); // N = wants to exit
}
// returns true if user wants to exit
bool ProceedWithMenu() {
cout << "1.\tAdd new record." << endl;
cout << "2.\tDelete record." << endl;
...
if (1 == value) {
...
}
if (5 == value) {
cout << "Application quitting... " << endl;
}
return (5 == value);
}
void mainLoop {
bool authenticated = false;
bool exitApp = false;
do {
if (!authenticated) {
exitApp = AuthenticateUser(authenticated);
} else {
exitApp = ProceedWithMenu();
}
// repeat authentication/menu until user decides to quit app
} while (!exitApp);
}
この例では、ちょうどdo {} while
のパワー、return
、および類似を説明しようとすると、まだかなり原油と単純化しすぎです。多くの場合continue
とbreak
は、goto
とラベルなしで、コード実行の流れを制御するのに非常に役立ちます。
gotoの使用は悪い習慣ですwhileループで置き換えようとします –
質問に表示されているコードは、[ヘルプ]で説明されている[mcve]の要件を満たしていません。 stackoverflow.comのすべての質問は、質問自体にすべての関連情報を含める必要があります。いつでも機能しなくなる外部のWebサイトへのリンクは許可されません。 –
"XはAまたはBです"とは英語で "X = AまたはX = B"です。あなたは「X = A、またはBは一種の真実」を持っています。 – molbdnilo