How to scan a data file and print a value on the screen when the number first exceeds a preset number

I am working in C and I am very new to this (2 weeks ago). Basically I have a file that has two columns of data separated by a space. I need to read from the file line by line and determine when the first time the second column exceeds a certain number. When he finds the row I'm looking for, I want her to print the corresponding number from the first column on the screen. Both columns are in numerical order.

To be more specific, column1 is the year, and column2 is the population. The first time the population exceeds a certain number, X, I want to print the corresponding date.

So far I have a code that scans and finds when the population is> X, and then prints the date, but prints each date with the population> X. I can’t get it to print only the first time it exceeds X and nothing else .

#include <stdio.h>
#include <stdlib.h>

int main()
{
  FILE *in;
  int ni,i;
  double d,p;

  if((in=fopen("pop.dat","r"))==NULL) {
   printf("\nCannot open pop.dat for reading\n");
   exit(1);
  }

  while(fscanf(in,"%lf %lf",&d,&p)!=EOF) {
    if (p>350) printf("\nDate is %f and Population is %f",d,p);
  }

  fclose(in);

  return(0);
}
+5
source share
2 answers

To get it for printing only the first, you can add code to such a function.

double getFirstDate(const char* filename)
{
    FILE *in;
    int ni,i;
    double d,p;

    if((in=fopen(filename,"r"))==NULL) {
    printf("\nCannot open pop.dat for reading\n");
    exit(1);
    }
    while(fscanf(in,"%lf %lf",&d,&p)!=EOF) {
    if (p>350)
    {
         printf("\nDate is %f and Population is %f",d,p);
         fclose(in);
         return p;
    }
    fclose(in);
    return -1;
}

Then call this function from the main

+1
source

You can also break the cycle as soon as you type the year.

     while(fscanf(in,"%lf %lf",&d,&p)!=EOF) {
       if (p>350) { 
         printf("\nDate is %f and Population is %f",d,p);
         break;
       }
    }
0
source

All Articles