I’m trying to write a block of code in C to parse an input text file with nothing but spaces and floating point numbers to count the number of columns in each row (or the number of floats in each row). What I have so far gives me 1 extra column in the counter for row 1 and seems to skip row 5 altogether.
HEre is the input file:
1.0 2.1 16.7 8.5
2.0 3.4
3.0 2.0 6.0
4.0 1.0
5.0
void count_columns(FILE*input, FILE*output)
{
//LOCAL DEFINITIONS
char scanned_char;
float scanned_float;
int column_count = 0;
int row_count = 0;
//COLUMN COUNT PER LINE
while((scanned_char = fgetc(input)) != EOF)
{
if(scanned_char != ' ' && scanned_char != ' ' && scanned_char != '
')
{
fscanf(input,"%f", &scanned_float);
column_count++;
}
if(scanned_char == '
')
{
row_count++;
fprintf(output,"Row %d of the input file has %d column(s).
", row_count, column_count);
column_count = 0;
}
}
printf("Column counts per row have been recorded to log.
");
return;
}
my output is as follows:
Row 1 of the input file has 4 column(s).
Row 2 of the input file has 2 column(s).
Row 3 of the input file has 3 column(s).
Row 4 of the input file has 2 column(s).
Why did it skip row 5?