Why is my program not returning the maximum and minimum integers of a text file?

Here's my code. Every time I run it, it gives me "Thread 1: breakpoint 1.1" when I assign INT_MAX to min.

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

int main() {
    int i, min, max;
    min = INT_MAX;
    max = INT_MIN;
    FILE* fp;
    fp = fopen("in.txt", "r");
    while (fscanf(fp, "%d", &i) != EOF) {
        if (i < min)
            min = i;
        if (i > max)
            max = i;
    }
    fprintf(fp, "%d %d", min, max);
    fclose(fp);
    return 0;
}

Upvotes: 0

Views: 44

Answers (2)

chqrlie
chqrlie

Reputation: 144740

The breakpoint does not seem related anything in the source at the line specified, probably a breakpoint set and remembered by your debugger.

Your program does not produce the expected output because you attempt to output to the file instead of stdout:

fprintf(fp, "%d %d", min, max);

Just change this line to:

printf("%d %d\n", min, max);

Note that there is another problem: if the file contains any character that is neither a digit nor a whitespace character, fscanf(fp, "%d", &i) will keep returning 0 without consuming this character from the input stream. Even worse, i is not modified if fscanf() returns 0.

You should change the main loop this way:

int n;

while ((n = fscanf(fp, "%d", &i)) != EOF) {
    if (n == 1) {
        if (i < min)
            min = i;
        if (i > max)
            max = i;
        }
    }
    getc(fp);
}

Upvotes: 1

Pedro Mu&#241;oz
Pedro Mu&#241;oz

Reputation: 285

Try changing:

fprintf(fp, "%d %d", min, max);

With:

printf("%d %d", min, max);

And look what prints in the terminal, are there the right numbers? (I think the answer will be yes).

If what you want is to print the numbers at the end of the file, use this code:

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

int main() {
    int i, min, max;
    min = INT_MAX;
    max = INT_MIN;
    FILE* fp;
    fp = fopen("in.txt", "r");
    while (fscanf(fp, "%d", &i) != EOF) {
        if (i < min)
            min = i;
        if (i > max)
            max = i;
    }
    fclose(fp);


    fp = fopen("in.txt", "a");
    fprintf(fp, "%d %d", min, max);
    fclose(fp);
    return 0;
}

Upvotes: 1

Related Questions