Is this syntax possible? (or something similar to it)

I want to take a string and contantiate a character to it, but only if the char is not a whitespace.

So something like this:
 
ms = (t != ' ') ? ms + t : ms;


Which works nicely, but if I wanted to use the overrided operator +=

could I do something like any of the following? (Nome of which seems to work.)
1
2
3
4
5
        ms += (t != ' ') ? t : NULL;
        ms += (t != ' ') ? t : 0;
        ms += (t != ' ') ? t : ''
        ms += (t != ' ') ? t : "";
        (t != ' ') ? ms += t : ;
Hi wft,

How about this:

1
2
3
4

if( ! isspace( t ) )
    ms += t;
I assume ms is a std::string


try this:

ms += (t!=' ')? t: '\0'; // use 0 as a char constant
Last edited on
std::strings keep \0 characters in their buffers, so the solution above may not be optimal
why would you want to use the ternary operator for this? It seems awfully inappropriate.

+1 to kooth's solution
@disch I'm just trying to learn and become more fluent in syntax I have had practically no experience using, and it is stylistically consistent with code I looked up on google. Why wouldn't I want to use a terniary operator for something like this?
The ternary operator is used to replace an if-else. In your case, as kooth's solution showed, you only need
an if() case.
again any reason why the following won't compile?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <string>
#include <iostream>
using namespace std; 
string str;
char t;
char null = '';

int main()
{
    str = "Hello ";
    do{

          t = cin.get();
        str += (t != ' ') ? t : null;
      }while (!isspace(t));
    str += '!';
    cout << endl << endl << endl << endl;
    cout << str << endl;
}


If I replace char null = '' with
 
char null = ' ';

It will compile but it will output:
Hello World !


If all I'm guilty of is trying to write elegant code, sue me.

Edit: jsmith I didn't see your post. I may consider using what kooth showed, but still am curious why don't they allow char null = '';
Last edited on
because you must have a character value in a character literal, it would be like doing
int i = 0x ;
It doesn't make sense
Topic archived. No new replies allowed.