开发者

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

开发者 https://www.devze.com 2023-04-07 14:07 出处:网络
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 f

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开发者_JAVA百科 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);
}


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


You can also break the loop once you have got the year printed.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号