0

直升机,

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

输入是字符数组:)

这是我检查文件中的空行的代码行,但它从不拾取例如空行..

我的代码读取 8 位十六进制值,我想在其无效(已排序)或有空行、带有空格或 EOF 的行时终止。

如果我的文件是这样的,它可以工作...... 11111111 11111111

^在空行上有一个空格,但如果没有空格,它就会进入一个无限循环,这很烦人。

#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);  
}
4

3 回答 3

2

您需要检查fgets. 该函数返回NULL信号“文件结束”。简单地说,试试这个:

if (!fgets(input, MAXIN, f))
    return INERR;
于 2012-02-18T16:56:35.640 回答
1

您可以使用此代码检查该行是否为空:

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);
}

并像这样测试:

fgets(line,YOUR_LINE_LEN_HERE,stdin);
    if (isEmptyLine(line) == false) {
        printf("not ");
    }
printf("empty\n");
于 2012-02-18T17:08:22.257 回答
0

你使用了错误的方法。您必须检查该行是否以 '\n' 结尾,以及该行中该字符之前的所有字符是否不可打印。仅检查第一个字符是不够的。

它应该是这样的:

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
于 2012-02-18T16:52:30.493 回答