Frage

Helo,

  if('\t' == input [0] ||'\v' == input [0] ||'\r' == input [0] ||'\n' == input [0] || '\0' == input[0] || '' == input[0])

input is the array of chars :)

This is the line of code ive got checking for a blank line in a file, but it never picks up a blank line for example..

My code reads in 8 digit hex values and i want to termiated when its invalid(already sorted) or when theres a empty line,line with white space or EOF.

It works if my file is like this... 11111111 11111111

^with a space on the empty line but if theres no space it just breaks in to a infitie loop this is very annoying.

#define MAXIN 4096 
  static char input[MAXIN]; 
  char last;
    /*Reading the current line */
  fgets(input, MAXIN, f);;
  if (input[8] == '\r') input[8] = '\0';
  /* First of all check if it was a blank line, i.e. just a '\n' input...*/
  if('\t' == input [0] ||'\v' == input [0] ||'\r' == input [0] ||'\n' == input [0] || '\0' == input[0] || '' == input[0])
  {printf("##EMPTY");return(INERR);}
  if ('\n' == input[0]) return(INERR); 

 if ((sscanf(input,"%8x%c",&result,&last) < 2)) return(INERR);
  if ('\n' != last) return(INERR);  
}
War es hilfreich?

Lösung

You need to check the return value of fgets. This function returns NULL to signal "end of file". Simply put, try this:

if (!fgets(input, MAXIN, f))
    return INERR;

Andere Tipps

You can use this code to check if the line is empty or not :

typedef enum { false = 0, true } bool;

bool isEmptyLine(const char *s) {
  static const char *emptyline_detector = " \t\n";

  return strspn(s, emptyline_detector) == strlen(s);
}

and test like this :

fgets(line,YOUR_LINE_LEN_HERE,stdin);
    if (isEmptyLine(line) == false) {
        printf("not ");
    }
printf("empty\n");

You use the wrong approach. You have to check whether the line ends with '\n' and whether all characters before that character in the line are not printable. It is not enough to check just the first character.

It should be something like that:

int len = strlen(input);

int isEmpty = 1;
if(input[--len] == '\n')
{
    while (len > 0)
    {
       len--;
       // check here for non printable characters in input[len] 
       // and set isEmpty to 0 if you find any printable chars

    }
}

if(isEmpty == 1)
   // line is empty
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top