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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With