for循环while while循环+附加条件

问题描述:

我有一个类似于此的循环。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

您可以使用为:

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

也许你的意思是

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

在while循环测试的条件的for循环total1=fsize(myfile)已成为部分的“初始化”的一部分。这是你的意图吗?

你确定你不想这样......

total1 = fsize(myfile); 

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

在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') {