C programming question. How do I flush a line of characters from a text file...

Lowell

New member
...then continue reading numbers? I have to read numbers from a text file and scan them into an array. The max numbers to be read is 99 but I want to stop at EOF. 1st how do I do that? and 2nd the text file contains characters. I need to flush that line then move on to the next line. How do I do that? The code I have now reads the numbers into the array but it doesn't stop at EOF or Flush any of the characters. Here is my code so far. The print sum at the end is me trying to get a count of all my addresses in my array. 10 points for sure for help and thanks in advance. I'll wait all day for an answer.

#include <stdio.h>
#include <stdlib.h>
#define FLUSH while (getchar() != '\n')

// Function declarations

int main (void)

{
// Local declarations

FILE* FP;
char f_n[250];
int rc;
int sum = 0;
float array[99];

// Statements

// Print Introduction and propmt user for the input file
printf("\nCOP 2220-81030 Project 4: Lowell Thomas\n\n");
printf("Enter File Name: ");
// Read file and error check
rc = scanf("%s", f_n);
if (rc != 1)
{
printf("No file name entered.\n");
exit(100);
}
// Open file and error check
FP = fopen(f_n, "r");
if (FP == NULL)
{
printf("Could not open file %s for read.\n", f_n);
exit(110);
}

// Scan text file into array and flush any invalid characters

for ( int i = 0; i < 98; i++)
{
rc = fscanf(FP, "%f", &array);
sum += 1;
if (rc == EOF)
break;
}
for (int i =0; i < 98; i++)
printf("\n%6.3f", array);

printf("\n\n%d", sum);

return 0;
 
Back
Top