I am a newbee in C++. Tried the following code:
while((char c = cin.get()) != 'q')
{ //do anything
}
when I try to compile, it fails with following
error: expected primary-expression before "char".
Please help me understand this
I am a newbee in C++. Tried the following code:
while((char c = cin.get()) != 'q')
{ //do anything
}
when I try to compile, it fails with following
error: expected primary-expression before "char".
Please help me understand this
You cannot have a declaration as a part of an expression.
while ((char c = cin.get()) != 'q') { ...
// |----------------| <---------------------- this is a declaration
// |-------------------------| <-------------- this is an expression
You can have a declaration directly inside the parentheses of the loop (not in any nested parentheses):
while (char c = cin.get()) { ...
but this stops on !c
, which is not what you want.
This will work:
while (int c = cin.get() - 'q') { // ugly code for illustrative purpose
c += 'q';
...
}
and so will this:
for (char c; (c = cin.get()) != 'q'; ) { // ugly code for illustrative purpose
...
}
Update: see also this SO question.
Try this:
char c;
while((c = cin.get()) != 'q')
{ //do anything
}
You are declaring the variable inside parantheses, hence the error:
while (char c = cin.get() != 'q')