1

What I want/need to accomplish is to read multipliable numbers within a text file.

I'm still a beginner to programming, and I'm unsure what to do.


Here's what my text file looks like:

23 35 93 55 37 85 99 6 86 2 3 21 30 9 0 89 63 53 86 79 

Here's what my code looks like:

FILE* infile = fopen("Outputnum.txt", "r");

for(int i=0; i<20; i++){

    fscanf(infile, "%d", &outputnum);
    return outputnum;

}

Keep in mind I have this code within a function, as my main goal is to read each number in the text file and record the smallest, and second smallest numbers. (Which is only 20 numbers) I figured a for-loop would be the best way to approach this problem, but I'm only returning my first number within the text file. (I'm trying to avoid using array's as it crashes my terminal)

1
  • Comments are not for extended discussion; this conversation has been moved to chat. Commented Oct 23, 2020 at 1:04

1 Answer 1

2

It's better if you don't use a loop with a hardcoded number limit. In my solution I read the numbers until there aren't any numbers left. You'll also not want to use a return statement inside your loop as that will exit the current function.

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

int main()
{
    int smallest = INT_MAX;
    int second_smallest = INT_MAX;
    int number;

    FILE *infile = fopen("numbers.txt", "r");
    if (infile)
    {
        while (fscanf(infile, "%d", &number) == 1)
        {
            if (number < smallest)
            {
                second_smallest = smallest;
                smallest = number;
            }
            else if (number < second_smallest)
            {
                second_smallest = number;
            }
        }
        fclose(infile);
    }

    printf("smallest: %d\n", smallest);
    printf("second smallest: %d\n", second_smallest);
    return 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Just a nit. After you open the file, check that the pointer isn't NULL. While your loop protects against attempting to read after a failed open, it complicates the placement of fclose(). If infile is validated after open, then you know fclose() is needed after the loop. Just relying on the loop to skip reading after a failed open relies of any open file to be closed after exit. Normally fine, but the OP mentions he want this in a function.
@DavidC.Rankin Good feedback, I updated the snippet to check for NULL and close the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.