This board has been very helpful to me and I really appreciate it. However, I'm stuck on a project and reading the book, asking on irc, and forums is not getting me any closer to seeing what I'm doing wrong. I actually got banned from an irc chan for aksing " noob" questions. This is what I need to do:
I need to read a text file. All the data in the file is on one line, like this:
12.4
wxy
0
text
4
-1
Now I only want the actual numbers from these files. When I get anything that is not a number I need to flush out the stream and get the next line. So far in my code when I get anything but a number the program stops: For example, after I read in 12.4 I get to wxy, I need to skip (flush) wxy and get 0 skip text and get 4 and get -1.
My problem is I just do not see how to flush out the stream. This is very frustrating especially since my lack of understanding is not because I'm not trying or being lazy or want someone to do it for me. I just don't see what I need to do here.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define FLUSH while (fgetc(sp) !='\n')
int stats(double data[], int b,char fileName[]);
int main(void){
char fileName[100];
double data[100];
FILE* sp;
int k = 0;
int b = 0;
int i = 0;
printf("Enter File Name: ");
scanf("%s",fileName);
printf("\n\n");
sp = fopen(fileName,"r");
if(!sp){ /* there is no file with given filename*/
printf("Error could not open file %s for read. \n\n",fileName);
exit(0);
}else if( fgetc(sp)==EOF){ /* no data in file,fileName valid */
printf("There were 0 files in %s.\n",fileName);
exit(0);
}
I think that I should call a
flush here before I read into data[]: I think that
I should open the buffer,check the buffer for
incorrect data (flush), read from buffer into data[]
while(k=(fscanf(sp,"%lf",&data[i++]) == 1)) {
b += k++ ;
}
fclose(sp);
stats(data,b,fileName);
return 0;
}