-2

Have made a program that reads a .csv file and stores the highest number in another file. The problem is that my program can't read comma separated numbers like 1,5,6,7,1,2. Here is the loop I need help to change

int i;
int max = 0;
int min = 0;
while (!feof(fp))
{
    fscanf( fp, "%d", &i);
    if (i < min)
    min = i;
    if (i > max)
    max = i;
}  

And this is what I print out:

    fprintf(q,"%d",max);
    printf("maximum value is %d \n", max);
    fclose(q);
    fclose(fp);
Mr.T
  • 27
  • 7

1 Answers1

1
#include <stdio.h>
#include <limits.h>

int main(void){
    FILE *fp = fopen("input.csv", "r");
    FILE *q  = fopen("max.txt" , "w");

    int i;
    int max = INT_MIN;
    int min = INT_MAX;

    while(1){
        int state = fscanf(fp, "%d", &i);
        if(state == 1){
            if (i < min)
                min = i;
            if (i > max)
                max = i;
        } else if(state == EOF){
            break;
        } else {
            char ch;
            fscanf(fp, " %c", &ch);
            if(ch != ','){
                fprintf(stderr, "\nformat error\n");
                break;
            }
        }
    }

    fprintf(q, "%d", max);
    printf("maximum value is %d\n", max);
    fclose(q);
    fclose(fp);

    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70