2010-07-20 148 views
0

我有一個類似於此的循環。for循環while while循環+附加條件

int total1, total2; 
for (total1 = fsize(myfile);;) { 
    total2 = fsize(myfile); 
    ... 
    ... 
    total1 = total2; 
} 

我想要做的是停止循環之前,將其轉換爲一個while循環並檢查額外的條件。

我願做這樣的事情:

while((total1 = fsize(myfile)) && input = getch() != 'Q') { 
    total2 = fsize(myfile); 
    ... 
    total1 = total2; 
} 

感謝

+6

有這裏有個問題嗎? – bstpierre 2010-07-20 22:15:49

+3

繼續前進。你應該將括號括起來((input = getch())!='Q')'。 – AShelly 2010-07-20 22:16:15

+0

其實出於某種原因,它不會進入循環...所以我不太確定我是否正確地執行while循環。 – 2010-07-20 22:17:21

回答

-1

您可以使用爲:

for(total1 = fsize(myfile); (input = getch()) != 'Q';) { 
    ... 
} 
+0

您可以*總是*使用「for」代替一段時間。只需將「while」改爲「for」,並在條件前後添加分號。 – 2010-07-20 22:28:28

+0

@ T.E.D .:當然。我試圖猜測OP正在尋找的答案 – 2010-07-20 22:37:34

0

也許你的意思是

while((total1 == fsize(myfile)) && ((input = getch()) != 'Q')) { 
    total2 = fsize(myfile); 
    ... 
    total1 = total2; 
} 

考慮到這些運營商=是signment ==是比較

+0

也許你的意思是不要把第二個'='改成'=='。 – IVlad 2010-07-20 22:22:37

+0

只是注意到,固定。 – JohnFx 2010-07-20 22:25:19

+0

幾乎不可能在沒有更多上下文的情況下確切地說出他的意思。 – 2010-07-20 22:30:19

0

在while循環測試的條件的for循環total1=fsize(myfile)已成爲部分的「初始化」的一部分。這是你的意圖嗎?

你確定你不想這樣......

total1 = fsize(myfile); 

while((input = getch()) != 'Q') { 
    total2 = fsize(myfile); 
    ... 
    total1 = total2; 
} 
0

在for循環的初始化只執行一次。該while相當於

for (total1 = fsize(myfile);;) { 

total1 = fsize(myfile); 
while (1) { 

你提到添加條件input = getch() != 'Q'

注意分配(=)比對照(!=)較低的優先級,所以分配到getch()input檢查該字符不是Q你需要括號圍繞assignement:

total1 = fsize(myfile); 
while ((input = getch()) != 'Q') {