简体   繁体   English

当数字首先超过设定数量时,如何扫描数据文件并将值打印到屏幕

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

I'm working in C and I'm very new at it (2 weeks ago). 我在C工作,我很新(2周前)。 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. 更具体地说,column1是一年,column2是一个人口。 The first time the population exceeds some number, X, I want to print the corresponding date. 人口第一次超过某个数字,X,我想打印相应的日期。

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. 到目前为止,我有代码扫描并查找当人口> X然后打印日期,但它打印的每个日期都有一个> X.我不能让它只打印第一次它超过X而没有别的。

#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 然后从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;
       }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM