For my C code, where I am reading a file and sorti

2019-09-21 01:00发布

I am doing an assignment which is: Find k largest elements of a file. Allocate an array of size k and while you read the numbers from the file, store the k largest numbers in the array. When you read the next element from the file, find if the array needs to be modified or not. Assume that next element read is 80. Since 80 is larger than the smallest element, we need to shift elements < 80 to the right by 1 position and create space for 80. In main() use argc and argv to read the filename and k from the user and compute and print the k largest elements. Name your program assign3.c First parameter is filename and second parameter is k. You need to use atoi()in stdlib.h to convert strings to integer.

My problem is that I am getting garbage values for both arr and sorted arr?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
int main(int argc, char *argv[])//
{
    FILE *iFile;//file pointer
    int i = 0, n, temp = 0, count = 0, j;
    int k = atoi(argv[1]);//convert strings into int    
    int *arr = (int *)malloc(k * sizeof(int));////allocate an array of size k
    iFile = fopen("a.txt", "r");//opens file
    if (iFile == NULL)
        return -1;
    while (feof(iFile) <= 0)
    {
        fscanf(iFile, "%d", arr);
        printf("arr= %d\n", arr);
        count = count++;
        for (i = 0; i < count; i++)                     //Loop for descending ordering
        {
            for (j = 1; j <= count; j++)             //Loop for comparing other values
            {
                if (arr[j] < arr[i])                //Comparing other array elements
                {
                    temp = arr[i];         //Using temporary variable for storing last value
                    arr[i] = arr[j];            //replacing value
                    arr[j] = temp;             //storing last value
                }
            }
        }
    }
    for (i = 0; i < k + 1; i++)
        printf("sorted arr is =%d\n", arr[i]);

    fclose(iFile);
    free(arr);
}

1条回答
We Are One
2楼-- · 2019-09-21 01:43

Use a while loop condition like this

While(!feof(iFile)) ....

feof() checks whether end of file is reached and returns 0 otherwise

查看更多
登录 后发表回答