Search code examples
cwhitespacefgets

Not recognising whitespace as char in loop?


I am reading text from a file and determining if the string begins with a # (excluding white space) and if there is no other char (excluding white space) preceding the # I write it to a separate file.
We are supposed to preserve the whitespace in the string. If there is white space before the # however it is not writing it. I am not sure if this is an fgets issue that I am unaware of or another issue.

I am sure my algorithm is a bit clumsy

int valid = 1;

while(fgets(str, 250,f1)!=NULL)
{
    printf("read strings: %s",str);/*my test*/

    for(i=0;i<strlen(str);i++)
    {
        if(str[i]=='#')
        {
            printf("strings: %s",str);/*my test*/
            for(j=0;j<i;j++)
            {
                if(isspace(str[j])!=0)
                {
                    valid=0;
                    break;
                }
            }
            break;
        }
        else
        {
            valid=0;
        }
    }
    if(valid==1)
    {
        fprintf(f2, str);
    }
    valid=1;
}

So from file:

#the cat sat on# the mat  
the sunny day  
    #cats sit on mats

it will write:

#the cat sat on# the mat

I have an exam next week and trying to get the best possible understanding I can in the short time I have left.


Solution

  • If the first character is a space it will go into this else:

        if(str[i]=='#')
        {
           <snip>
        }
        else
        {
            valid=0;  // This line is executed if str[0] is space
        }
    

    A better approach would be to skip until you find the first non-space character and if it is a '#' then print the line else don't print it.