2012-10-13 95 views
0

我是C++中的新手。嘗試下面的代碼:這個C++構造有什麼錯誤?

while((char c = cin.get()) != 'q') 
{ //do anything 
} 

,當我嘗試編譯時,出現以下

error: expected primary-expression before "char".

請幫助我瞭解這個

回答

2

您不能將聲明作爲表達式的一部分。

while ((char c = cin.get()) != 'q') { ... 
//  |----------------| <---------------------- this is a declaration 
//  |-------------------------| <-------------- this is an expression 

可以有直接的循環(不是在任何嵌套的括號)的括號內的聲明:

while (char c = cin.get()) { ... 

但這停在!c,這是不是你想要的。

這將工作:

while (int c = cin.get() - 'q') { // ugly code for illustrative purpose 
c += 'q'; 
... 
} 

,因此將這樣的:

for (char c; (c = cin.get()) != 'q';) { // ugly code for illustrative purpose 
    ... 
} 

更新:也this SO question看到。

1

試試這個:

你是聲明變種內部的變量,因此錯誤:

while (char c = cin.get() != 'q') 
+0

是的,我知道它會工作。但是我想知道爲什麼我的構造完全通過.. – bubble

+0

您可能想嘗試'while(char c = cin.get()!='q')' – bubble

+0

@bubble,有聲明並且有表達式。語句不能用作表達式的一部分。 'char c = ...'是一個聲明。 –