Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scan a file of data and print a value to the screen when a number first exceeds a set number

Tags:

c

scanf

I'm working in C and I'm very new at it (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 some number. When it finds the row I'm looking for, I want it to print to the screen the corresponding number from the first column. Both columns are in numerical order.

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

So far I have code that scans and finds when the population > X and then prints the date, but it prints every date that has a population > X. I can't get it to only print 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);
}
like image 938
user963140 Avatar asked Nov 13 '22 16:11

user963140


1 Answers

To get it to print just the first you could add the code to a function like this.

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 main

like image 102
Stuart Jones Avatar answered Dec 20 '22 09:12

Stuart Jones