Reputation: 85
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;
}
Upvotes: 0
Views: 153
Reputation: 103
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?
Upvotes: 0
Reputation: 2796
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; }
Upvotes: 1
Reputation: 6178
'#' is not a digit, so you are probably hitting the continue
before making it to the else if
.
Upvotes: 4