简体   繁体   English

如何在 c 编程中找到 atof function 中的数字总和

[英]How can i find the sum of numbers in atof function in c programming

  1. The code has to read the text file代码必须读取文本文件
  2. extract numbers and find their average提取数字并找到它们的平均值
  3. I have already extracted numbers and placed them in a ATOF function我已经提取了数字并将它们放在 ATOF function

My code can read the file and extract numbers but i dont know how to find the sum of the numbers extracted and find the average.我的代码可以读取文件并提取数字,但我不知道如何找到提取的数字的总和并找到平均值。 I need help in the modification of my code cause am not too familiar with the atof function我在修改代码时需要帮助,因为我对 atof function 不太熟悉

Sample input text file示例输入文本文件

LivingTemp1,17.8
LivingTemp2,17.9
LivingTemp1,18.1
LivingTemp2,18.2
LivingTemp1,18.5
LivingTemp2,18.6
LivingTemp1,19.0
LivingTemp2,19.0
LivingTemp1,19.5
LivingTemp2,19.6
LivingTemp1,20.0
LivingTemp2,20.1
LivingTemp1,20.6
LivingTemp2,20.6
LivingTemp1,19.8
LivingTemp2,19.8
LivingTemp1,19.4
LivingTemp2,19.5
LivingTemp1,19.0
LivingTemp2,19.1
LivingTemp1,18.5
LivingTemp2,18.6
LivingTemp1,18.0
LivingTemp2,18.1

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

void main()
{
    FILE *fp = fopen("test.txt", "r"); `opening the text file`
    FILE *fp1 = fopen("test.txt", "r");
    const char s[2] = ", ";
    char *token;
    char c;
    int count = 1;
    int i;
    int number[24];

    if(fp != NULL)
    {
        char line[24];

        while(fgets(line, sizeof line, fp) != NULL)
        {
            token = strtok(line, s); // ignoring the commas

            for(i=0;i<2;i++)
            {
                if(i==0)
                {
                    //printf("%s\t",token);
                    token = strtok(NULL,s);
                } else {    
                    double num = atof(token);
                    printf("%.1f\n",num);   // printing the extracted numbers    
                }
            }
        }

        for (c = getc(fp1); c != EOF; c = getc(fp1)){
            // countingthe number of lines the text file contains
            if (c == '\n') // Increment count if this character is newline
                count = count + 1;
        }

        printf("The file has %d lines\n ",count);    

        fclose(fp);
    } else {
        perror("test.txt");
    }
}

Your task is very simple: Convert the second token of each line into a floating-point number.你的任务很简单:将每行的第二个标记转换为浮点数。 If the conversion succeeds, add that number to the sum and increase the data count.如果转换成功,将该数字添加到总和并增加数据计数。 Finally, report your data, but beware of division by zero.最后,报告您的数据,但要注意除以零。

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

int main(void)              // main returns int, not void
{
    char line[80];          // make the line bige enough
    int count = 0;          // the count starts at zero, not at one
    double sum = 0.0;

    const char *filename = "test.txt";
    FILE *fp = fopen(filename, "r");

    if (fp == NULL) {
        fprintf(stderr, "Could not open '%s'.\n", filename);
        exit(1);
    }

    while (fgets(line, sizeof line, fp)) {
        const char *sep = ",";              // don't include the space
        char *token = strtok(line, sep);

        if (token == NULL) continue;        // skip empty lines

        token = strtok(NULL, sep);

        if (token) {
            double T = atof(token);

            if (T) {
                sum += T;
                count++;
            }
        }
    }

    fclose(fp);

    if (count) {
        printf("Number of measurements: %d\n", count);
        printf("Average temperature:    %g\n", sum / count);
    } else {
        puts("No data!");
    }

    return 0;
}

The function atof is very simple and returns 0.0 if a number cannot be converted. function atof非常简单,如果无法转换数字,则返回 0.0。 That means you canot distinguish between the actual number 0, which is a likely temperature in centegrade, and conversion failure.这意味着您无法区分实际数字 0(可能是摄氏度的温度)和转换失败。 The function strtod offers you better disgnostics. function strtod为您提供更好的诊断。

Here is a simpler version:这是一个更简单的版本:

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

int main()
{
  int living, n, count=0;
  double value, sum = 0.0;

  FILE *fp = fopen("test.txt", "r"); //`opening the text file`
  if( !fp ) err(EXIT_FAILURE, "no input");

  while( (n = fscanf(fp, "LivingTemp%d,%lf ", &living, &value)) == 2 ) {
    count++;
    sum += value;
  }

  if( n != EOF ) {
    errx(EXIT_FAILURE, "failed to parse line %d", count);
  } 

  if( !feof(fp) ) {
    err(EXIT_FAILURE, "failed to read file");
  }

  printf( "average of %d values is %f\n", count, sum / count );

  return EXIT_SUCCESS;
}

Just for grins, I also parse the "living" number.只是为了笑,我还解析了“活着”的数字。 ISTM in a real-world case you'd need to compute averages and counts by identifier. ISTM 在实际情况下,您需要按标识符计算平均值和计数。 The value is parsed out in case you want it.如果您需要,该值将被解析出来。

Normally I recommend reading a line before scanning it.通常我建议在扫描之前阅读一行。 In your case your input is well specified, and you can scan it directly.在您的情况下,您的输入已明确指定,您可以直接扫描它。 Note this also compensates for blank lines because the format string ends in whitespace.请注意,这也补偿了空白行,因为格式字符串以空格结尾。 It has the disadvantage of aborting on the first failed parse, rather than reporting errors and continuing to end of file.它的缺点是在第一次失败的解析时中止,而不是报告错误并继续到文件结尾。

The scanf (3) functions are IMO generally under-appreciated. scanf (3) 函数通常被 IMO 低估。 One scanf statement saves you reinventing tokenizing, skipping whitespace, and individually converting each component.一个 scanf 语句可以帮助您重新发明标记化、跳过空格和单独转换每个组件。 Note for example that failure to convert shows up in the conversion count (returned by the function).例如,请注意转换失败会显示在转换计数中(由函数返回)。

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

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