简体   繁体   中英

Garbage data printed after reading a file and putting integers in ascending order

I am working on this code to read the file test_numbers.txt , and take the numbers, and print them in ascending order. When I run my program it outputs:

7

8

9

10

40

41

42

43

50

-1843443791

This would be correct. The numbers from 7-50 are correctly placed, but the problem pertains to the -1843443791. I have tried checking the text file and making sure there are no errors but I can't seem to find the issue. This is why it makes me think there is an issue with the code that I cannot spot. Here is the text file: https://github.com/untamedspud/testNumbers . I am only concerned about the test_number.txt file currently.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void insert_in_array_ascending(int array[], int size);
int readfile(int array[], char *fname);
void print_int_array(int array[], int size);
int main()
{
    int primary[100];
    int count = 0;
    count += readfile(primary, "test_numbers.txt");

    insert_in_array_ascending(primary, count);
    count++;

    print_int_array(primary, count);

}
void insert_in_array_ascending(int array[], int size)
{
    int i, j, temp;
    for (i = 0;i<size;++i)
    {
        for (j=i+1;j<size;++j)
        {
            if (array[i]>array[j])
            {
                temp =  array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
    }
}
int readfile(int array[], char *fname)
{
    int i = 0;
    FILE *file = fopen(fname, "r");
    while(fscanf(file, "%d", &array[i]) != EOF)
    {
        insert_in_array_ascending(array, i);
        i++;
    }
    return i;
}
void print_int_array(int array[], int size)
{
    for(int i=0;i<size;i++)
    {
        printf("%d", array[i]);
        printf("\n");
    }
}

In your original file, you did not have the "readfile" function, and the reading happened in the main function. There, you needed a counter - and that was "count", incremented after each read.

Then you moved that section of code into a separate function, but you maintained the cycle framework (for example, you add readfile's return to a count initialized to zero, which is equivalent to assigning readfile's return to count). More importantly, you forgot the count increment :

int count = 0;
count += readfile(primary, "test_numbers.txt");

insert_in_array_ascending(primary, count);
count++;
print_int_array(primary, count);

The net result is that print_int_array prints one item more than it read, and that last item's content is indefinite. Hence your garbage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM