2017-02-18 42 views
0

我需要爲我的編程類創建菜單驅動輸入[Case/Switch Statement]。我的教授沒有教我們如何創建一個菜單,而且我很難理解我的課本。我需要菜單循環,直到用戶選擇退出來終止程序。我還需要在案例/開關中使用默認的錯誤消息,錯誤消息必須描述由用戶引起的錯誤 。菜單驅動輸入Do循環

任何人都可以指導我做什麼?我只需要開始,其餘的事情通常對我來說很自然。

#include<iostream> 
#include<fstream> 
#include<string> 
using namespace std; 

ofstream ofs("bafia_lab5.txt"); 

string msg = "eofmessage "; 
string cno = "blank "; 
string name = "blank "; 
string dat = "2/16/17 "; 
string lab = "blank "; 
string phn = "blank "; 
string sum = "Create menu that allows users to choose between While Loop, Do Loop, For Loop and quit. "; 
string whlo = "While Loop:"; 
string dooo = "Do While Loop:"; 
string forro = "For While Loop"; 
int counter; 
int option; 

//Header for lab with name, class#, due date, and lab number 
void hdr() 
{ 
    ofs << name << cno << dat << lab << endl; 
    ofs << endl; 
} 

void menu() 
{ 
    do 
    { 
     ofs << "1. Do Loop " << dooo << endl; 
     ofs << "2. While Loop " << whlo << endl; 
     ofs << "3. For Loop" << forro << endl; 
     ofs << "4. Quit " << endl; 
     ofs << endl; 
    } while (option <= 4) 
} 


//Function for "while loop" 
void whl() 
{ 
    ofs << whlo << endl; 
    counter = 1; 

    while (counter <= 10) 
    { 
     ofs << counter << endl; 
     counter++; 
    } 
    ofs << endl; 
} 

//Function for "do while loop" 
void doo() 
{ 
    ofs << dooo << endl; 
    counter = 1; 

    do 
    { 
     ofs << counter << endl; 
     counter++; 
    } while (counter <= 10); 
    ofs << endl; 
} 

//Function for "for loop" 
void forr() 
{ 
    ofs << forro << endl; 
    for (counter = 1; counter <= 10; counter++) 
    { 
     ofs << counter << endl; 
    } 
    ofs << endl; 
} 

//Function for description of lab 
void ftr() 
{ 
    ofs << sum << endl; 
    ofs << endl; 
} 

//End of file function with name, class#, due date, and lab number 
void eof() 
{ 
    ofs << msg << name << cno << dat << lab << endl; 
} 

//Call all functions 
int main() 
{ 
    hdr(); 
    menu(); 
    whl(); 
    doo(); 
    forr(); 
    ftr(); 
    eof(); 
    return 0; 
} 
+0

有沒有在這個問題無關手頭的工作很多垃圾。這些字符串是什麼?除非你要把東西本地化,否則最好儘可能地將它們放在他們使用的地方。另外,作爲編程中最重要的事情之一是命名事物,請**選擇描述性的名稱**。 「dooo」不是。 – tadman

+0

@tadman我的教授使用把所有東西都放在這樣的字符串中。我沒有拿出他對不起的名字。 whlo是while循環void,dooo是for循環,forro是循環void。 – polskiebmw

+0

我剛剛搜索了「switch語句菜單C++」,並且有很多非常清晰的示例。如果你不明白教科書中的內容,請使用其他資源。這是一個基本概念。當然,每個人都必須從某個地方開始,但沒有人能說服你如何做得更好。這將是值得您的時間。如果你仍然有麻煩回來問問題,你應該先做。 – RSon1234

回答

2

你可以做這樣的事情:

char choice = 'y'; 
while(choice == 'y' || choice == 'Y'){ 
    cout << "Enter choice : "; 
    cin >> choice; 
    switch(choice) { 
     case 'a' : cout << "This is case-a\n"; 
        //do something 
        break; 
     ... 
     default : //invalid choice alert 
        break; 
    } 
    cout << "Enter y/Y to continue else anything else to exit : "; 
    cin >> choice; 
}