-1

I'm building an assembly compiler in C, and I need to print only line which contain code (alphanumeric characters). However my compiler doesn't recognize a string pointed to by fgets() as empty, since it sometimes contains whitespace characters.

How do I make a condition, to only print lines containing alphanumeric characters?

My code looks like this:

while(fgets(Line,256,Inputfile)!=NULL)
{   
    i=0;

    while(Line[i]!='\n')
    {               
        Instruction[i]=Line[i]; 
        i++;    
    }

        printf("%s \n",Instruction);
}

Thanks,

Brian McFarland
  • 9,052
  • 6
  • 38
  • 56
Marcus
  • 25
  • 1
  • 5
  • Use **while( ! isspace( *strptr++) )** somewhere. – Arif Burhan Mar 07 '16 at 19:38
  • 4
    This question could be made much more simple by throwing out any reference to building a compiler, assembler, etc. Those details have nothing at all to do with the problem at hand, and extra details only make communications more difficult. – mah Mar 07 '16 at 19:38
  • The fact that you are building a compiler (or assembler?) is irrelevant, so the tag was removed. This is just a basic C I/O and string question. The function `strcspn` probably does what you want if you *only* want to ignore lines with whitespace. – Brian McFarland Mar 07 '16 at 19:39
  • Apologies for referencing compiler - I am relatively new to this website an I assumed I should give a little context of my problem. Thank you for your understanding. Will remember for next time :) – Marcus Mar 08 '16 at 01:20

3 Answers3

0

You have to trim the result of the fgets. You can refer to this answer to view an example that shows how to trim an array of characters in C.

I hope this can help you.

Community
  • 1
  • 1
PieCot
  • 3,564
  • 1
  • 12
  • 20
0

Do I understand you right? You want to ignore lines with only whitespaces?

while(fgets(Line,256,Inputfile)!=NULL)
{   
   i=0;
   int flag = 0;
   while(Line[i]!='\n')
   {               
      if(Line[i] != ' ' && Line[i] != '\t'){
         flag = 1;
      }
      Instruction[i]=Line[i]; 
      i++;    
   }
    if(flag == 1){
       printf("%s \n",Instruction);
    }
}
FlowX
  • 102
  • 12
  • Thank you very much for this - that's exactly what I was trying to do! BTW, what is `'\t'` ? Thanks! – Marcus Mar 08 '16 at 01:16
0

Add a function isLineToIgnore() in which you check whether the line contains any alphanumeric characters or not.

int isLineToIgnore(char* line)
{
   for (char* cp = line; *cp != '\0'; ++cp )
   {
      if ( isalnum(*cp) )
      {
         // Don't ignore the line if it has at least one
         // alphanumeric character
         return 0;
      }
   }

   // The line has no alphanumeric characters.
   // Ignore it.
   return 1;
}

and then call the function.

R Sahu
  • 204,454
  • 14
  • 159
  • 270