有關C++的loop back to beginning

2011-10-05 8:50 am
情況如下:
input a character, 'q' for quit: a <先問一條問題
the character you typed is a

input a character, 'q' for quit: b <如何返回開始再問同一條問題?
the character you typed is b

input a character, 'q' for quit: 1 <如是者, 繼續問
the character you typed is 1

input a character, 'q' for quit: q <直接打到答案先出現QUIT
the character you typed is q

QUIT!

小弟試過用switch 但只出一次, 就while loop又唔知點整
小弟係初哥 應該點做??
更新1:

actually I write in Dev-C++, but I save file in '.c' . as i write in 'do-while', the output does not like the above. it repeats 'input a character, 'q' for quit: the character you typed is' between the next asking.

更新2:

I write like this: do { printf("Please input a character and then ,'q' for quit:"); scanf("%c", &character); printf("The character you typed is [%c]\n\n", character); }while(character!='q'); printf("The program quits, as you wanted...");

回答 (1)

2011-10-05 12:55 pm
✔ 最佳答案
In this case you need a do while loop instead of a while loop because

you want to prompt the user to enter a character at least once and decide

what you are going to do after that and if the user don't enter the letter 'q' it will

keep prompting the user to enter a character so you can do it this way:

do{
cout<<"input a character,'q' for quit: ";
cin>>character;
}while(character!='q');

cout<<"QUIT!";

2011-10-05 04:56:59 補充:
and switch will only happen once unless it's in a loop


收錄日期: 2021-04-23 23:03:28
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20111005000051KK00065

檢視 Wayback Machine 備份