简体   繁体   中英

ignore chars between 2 chars

Im looking through a file. if I run into a '#' I want to ignore everything until I get to '\\n' . my current logic is not working.

Im trying to strip comments from the file I think the problem has something to do with my logic in the second while loop

int wishforint(FILE *in)
{
char c;
int d;
int i=0;
int smarr[5];

while(i<5)
{
   fscanf(in, "%c", &c);
   printf("c is %c\n",c);

   if(isdigit(c))
   {
      ungetc(c, in);
      fscanf(in, "%d", &d);
/*add this later. 
return d;
*/
      smarr[i]=d;
      printf("smarr[%d]= %d\n",i,d);
      i++;
   }
   else if(c=='#')
   {
      while(fscanf(in,"%c",&c) != EOF && c != '\n')
      {}
      break;
   }
}


   printf("Width is = %d\n", smarr[1]);
   printf("Height is= %d\n", smarr[2]);
   printf("Max value= %d\n", smarr[3]);

   return 7;
}

“#”不是数字,因此您可能要先单击“ continue然后再将其转到else if

Two problems with the code.

First fscanf does not check for EOF. Fix:

//fscanf(in, "%c", &c);
    if (fscanf(in, "%c", &c) == EOF) { break; }

Secondly, there ought not to be a 'break' in the '#' clause:

else if(c=='#')
    {
      while(fscanf(in,"%c",&c) != EOF && c != '\n')
      {}
      //break;
    }

May be usage of sscanf and fgets will be more easy?

Probably something like this:

while (fgets(buf, BUF_LENGTH, in) != NULL){
    errno=0;
    if ((sscanf(buf, "%d", &d) == 0) && (errno == 0)){
      //we have a comment
      continue;
    }else if(errno != 0){
      //error handling
    }
    //we have a value
    smarr[i]=d;
    i++;
}

It should works well with one-value-in-column file. Where comments starts from begin of new line or after value.

Can you show example of input data?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM