我正在開展一個學習 C 的教育專案,其中特定標簽包括正在研究的特定主題的代碼。但是,在每個代碼塊的末尾,我希望編譯器詢問用戶是要退出還是從頭開始計數:
void main(void)
{
beginning:
printf("goto : \n 1) pointers \n 2) classes \n 3) \n 4) \n 5) \n ");
scanf_s("%d", &input);
switch (input)
{
case 1:
goto pointers;
case 2:
goto classes;
case 3:
case 4:
case 5:
default:
printf("wrong try again \n");
goto beginning;
}
pointers:
.....
classes:
......
}
檢查用戶想要什么的代碼:
do {
printf("1 for exit and 2 for return menu \n");
scanf_s("%d", &reserved);
if (reserved == 2) { goto beginning; }
else if (reserved == 1) { exit; }
else { printf("wrong number, put a valid one you little..!"); }
} while (reserved != 1 && reserved != 2);
我試圖將它轉換為一個函式,但問題是labels定義在主函式的放置端,所以我只想讓編譯器在呼叫它時放置我的函式,而不是從一開始就對其進行評估。
uj5u.com熱心網友回復:
構建代碼的正確方法是(偽代碼如下):
Do
PrintPrompt()
input = ReadInput()
switch (input)
case 1: DoFirstThing()
case 2: DoSecondThing()
...
default: PrintError()
While (UserWantsToContinue())
goto在這里使用(或幾乎在任何地方,請參閱此問題的答案)確實沒有任何理由。對于規范的論文去這里。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425959.html
