While coding very simple program for removing blanks, tabs, newlines I came across something I don’t actually catch on first; even though if condition is true only when tab, space or newline doesn’t exist it’s still executed with the mentioned for some reason.. here is the code
#include <cstdio>#include <cstring>
#include <stdio.h>
#include <string.h>
#define LGT 100
void rem(char s[])
{
int i;
for(i=(strlen(s)-1);i>=0;i--)
if(s[i]!=' ' || s[i]!='\t' || s[i]!='\n')
break;
s[i+1]='\0';
}
int main(void)
{
char v[LGT]={"sdsfg\t"};
rem(v);
printf("%s\n",v);
getchar();
}
The problem is that
Is always true. If
s[i]is a space, then the latter two checks are true. If it’s not a space, them the first check is true.To fix this, change these ors to ands:
Or, even better, use
isspace: