Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

arrays - For my C code, where I am reading a file and sorting it is giving me garbage outputs. Why?

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
", 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
", arr[i]);

    fclose(iFile);
    free(arr);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a while loop condition like this

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...