Why is mine or expression not working, C ++?

I am trying to create a function that will replace 0, 1 or 2 spaces in a string. I am going to do this by repeating a line and comparing each individual character.

My function will work if I compare str_in [i] == '0' , but if I add either an operator, it will not return anything.

Excerpt:

string omit_num( string ) {
    int i ;

    str_len = str_in.length();
    str_out = "" ; 

    for( i = 0 ; i < str_len ; i ++ ){
         cout << str_in[i] << endl; 
         if ( str_in[i] == '0' || '1' || '2') 
            app = " " ;
         else
             app = str_in[i];
         str_out.append(app) ; 
    }
    return str_out; 

}
+3
source share
11 answers

You need

if ( str_in[i] == '0' ||  str_in[i] =='1' ||  str_in[i] =='2') 
+11
source

You will have to repeat the test every time, '1', '2' by themselves are basically small ints and evaluated as true. It should look like this:

if (str_in[i] == '0' || str_in[i] == '1' || str_in[i] == '2')
+6
source

str_in[i] == '0' || '1' || '2' :

str_in[i] == '0'
'1'
'2'

ASCII, "0" 48, "1" 49, "2" 50. , ( ).

, str_in[i] == '0' || str_in[i] == '1' || str_in[i] == '2'

+4
if (str_in[i] == '0' || str_in[i] == '1' || str_in[i] == '2')

, ,

switch (str_in[i]) {
  case '0':
  case '1':
  case '2': app = " " ;
            break;
  default:  app = str_in[i];
}
+4

'1' '1', '1' true. , , .

:

if ( str_in[i] == '0' || str_in[i] == '1' || str_in[i] == '2' )

+3

if : i '0', '1' - true, '2' - true. '1' '2' , .

: str_in[i] == '0' || str_in[i] == '1' || str_in[i] == '2'

+3

Not sure about the logic in general, but the logic here is specifically incorrect. Replace

if ( str_in[i] == '0' || '1' || '2') 

with

if ( str_in[i] == '0' || str_in[i] == '1' || str_in[i] == '2') 
+1
source

Change your if statement to:

if ( str_in[i] == '0' || str_in[i] == '1' || str_in[i] == '2') {
...
}
+1
source
string omit_num( string ) { 
int i ; 

str_len = str_in.length(); 
str_out = "" ;  

for( i = 0 ; i < str_len ; i ++ ){ 
     cout << str_in[i] << endl;  
     if ( str_in[i] == '0' || '1' || '2')  
        app = " " ; 
     else 
         app = str_in[i]; 
     str_out.append(app) ;  
} 
return str_out;  

}

this will work as follows:

string omit_num( string ) { 
int i ; 

str_len = str_in.length(); 
str_out = "" ;  

for( i = 0 ; i < str_len ; i ++ ){ 
     cout << str_in[i] << endl;  
     if ( (str_in[i] == '0') || (str_in[i] == '1') || (str_in[i] == '2'))  
        app = " " ; 
     else 
         app = str_in[i]; 
     str_out.append(app) ;  
} 
return str_out;  

}

+1
source

You need to apply the equality operator in each || expression:

if (str_in[i] == '0' || str_in[i] == '1' || str_in[i] == '2')
+1
source

If you use C ++, use the standard library already:

std::replace_if( s.begin(), s.end(), [](char a){return a=='0'||a=='1'||a=='2';}, ' ');
0
source

Source: https://habr.com/ru/post/1772927/


All Articles