tags:

views:

121

answers:

1

Friends

I want to integrate the following code into the main application code. The junk characters that come populated with the o/p string dumps the application The following code snipette doesnt work..

void stringCheck(char*);

int main()
{
    char some_str[] = "Common Application FE LBS Serverr is down";
    stringCheck(some_str);
}


void stringCheck(char * newString)
{
    for(int i=0;i<strlen(newString);i++)
    {
        if ((int)newString[i] >128)
        {

TRACE(" JUNK Characters in  Application Error message FROM DCE IS = "<<(char)newString[i]<<"++++++"<<(int)newString[i]);

        }
    }
}

Can someone please show me the better approaches to find junk characters in a string..

Many Thanks

+5  A: 

Your char probably is represented signed. Cast it to unsigned char instead to avoid that it becomes a negative integer when casting to int:

if ((unsigned char)newString[i] >128)

Depending on your needs, isprint might do a better job, checking for a printable character, including space:

if (!isprint((unsigned char)newString[i])) 
    ...

Note that you have to cast to unsigned char: input for isprint requires values between 0 and UCHAR_MAX as character values.

Johannes Schaub - litb
for(int i=0;i<strlen(newString);i++) { if (!iscntrl(newString[i]) }Doesnt work
ronan
like i said, cast to unsigned char first. the behavior is undefined if you don't. existing implementations use the value to index in an array. if you don't cast, they will index into some arbitrary location. chances are that it causes some weird things to happen
Johannes Schaub - litb
also http://www.catb.org/~esr/faqs/smart-questions.html#id307849 ...
Johannes Schaub - litb
Thanks litb It worked
ronan