I've started learning C and found myself in trouble with a simple problem. All that I need to do is to remove repeating spaces from stdin using a while loop, but I want to solve this problem with ternary if expressions.
Here's my code:
#include <iostream>
using namespace std;
int main()
{
bool space = false; // set to true if the symbol is ' '
// and reset to false if it's not
// if current symbol is ' '
// and bool is true (previous was also ' ') then
// I want to go to the next iteration
// without printing the current symbol which is repeating ' '
char c = '\0';
while (cin.get(c)) {
c != ' ' ? space = false : !space ? space = true : continue;
cout << c;
}
return 0;
}
And when I try to compile this code I get an error message:
expected primary-expression before 'continue'
How do I get out of this situation?
Upd: Using usual ifs is not the answer that I want because I'm not new to programming, I'm new to C . I know how to solve this with ifs, just want to try other ways.
CodePudding user response:
I assume that this obscure construction:
c != ' ' ? space = false : !space ? space = true : continue;
is meant to be this:
if(space && c == ' ') continue;
space = c == ' ';
That is, if the previous character was a space and the current is too, continue
, otherwise, set space
to true
if the current is a space and false
if it's not.
I want to solve this problem with ternary if expressions.
e1 ? e2 : e3
The result of e2
and e3
must be convertible into the same value type (see expr.cond
). continue
is a statement (expression). It can't be convered to bool
as it should have to be in this case - so, you need to split up your expressions and put the statement where it belongs.
You can however use a throw
expression like this:
while (cin.get(c)) {
try {
c != ' ' ? space = false : !space ? space = true : throw 0;
cout << c;
} catch(...) {}
}
... and this is exactly what exceptions should not be used for - but it "solves" your struggle with the conditional operator.