Hass Sugma
Hass Sugma

Reputation: 21

How to read only the first value of a file, then go to the next line?

So I am writing a program that reads data from an input file and prints it out.

One of my tasks is to store the total number of records (10), and check which number reoccurs the most.

The sample input file consists of this;

1265 -37.817365 144.968783 6/8/19 10 1726 -37.810009 144.962800 6/8/19 10 1726 -37.809657 144.965221 6/8/19 11 1726 -37.867842 144.976916 6/8/19 14 1328 -37.913256 144.985346 6/8/19 14 1265 -37.822464 144.968863 6/8/19 14 1654 -37.830386 144.979659 9/8/19 11 1726 -37.822464 144.968863 1/9/19 14 1654 -37.817365 144.968783 1/9/19 15 1408 -37.845590 144.971467 1/9/19 16

Now the only number I want to be checking is the first value, and seeing which of these numbers comes up the most and printing that number. From this file, it would be number 1726.

I am new to arrays and storage, but this is what I have so far;

int i=0;
int num;
int integers [256];
while(fscanf(stdin, "%d", &num) > 0) {
    integers[i] = num;
    i++;
}
printf("\n%d", num);

Where do I go from here? I am pretty stuck and not sure how to achieve my desired outcome.

Upvotes: 2

Views: 70

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50776

You probably want something like this:

...
int i=0;
int num;
int integers [256];
char linebuffer[100];
while(fgets(linebuffer, sizeof linebuffer, stdin) != NULL)
{
  if (sscanf(linebuffer, "%d", &num) == 1)
  {
    integers[i] = num;
    i++;
  }
}
...

This is untested code, there may be errors, but you should get the idea. Especially if the file has more than 256 lines you may get an array index overflow and hence undefined behaviour.

Upvotes: 2

Related Questions