【问题标题】:c language : read file content as numbers and add them togetherc语言:将文件内容读取为数字并将它们相加
【发布时间】:2010-12-01 01:04:01
【问题描述】:

我在一个名为 values.txt 的文本文件中有以下内容

1 4 
2.5 3.76
122 10
277.543 
165.4432

我正在尝试读取此文本文件的内容,并将每两对相加并输出结果... 输出将是这样的:

1 Pair:(1, 4) = 5

2 Pair:(2.5, 3.76)= 6.26

等等..

我是这样打开文件的

int c;
FILE myfile; 

myfile= fopen("values.txt", "r"); 
if ( myfile == NULL ) { 
  printf("Cannot open TEXT file\n");
  return 1; 
}

double aa,bb;
while ( (c = getc(myfile) ) != EOF ) { 
    // HERE SHOULD I DO THE OUTPUT BUT HOW?
}

非常感谢任何帮助..

语言 = C

【问题讨论】:

  • 为什么使用return 1; 而不是return 0;

标签: c parsing file


【解决方案1】:

以下代码符合您的预期。 myfile 应声明为 FILE*。 fopen 返回一个指向 FILE 结构的指针。如果文件非常大,我建议读取大尺寸的缓冲区(例如:65535 等)并逐个字符地解析它并将其转换为浮点值。它减少了系统调用开销,这比将文本处理为浮点值需要更多时间。

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

main(int argc, char *argv[])
{
    FILE* myfile; 

    myfile = fopen("values.txt", "r"); 
    if ( myfile == NULL ) { 
        printf("Cannot open TEXT file\n");
        return 1; 
    }

    double aa,bb;
    while (2 == fscanf(myfile, "%lf %lf", &aa, &bb)) {
        printf("%lf\n", aa+bb);
    }
    return 0;
}

【讨论】:

  • 感谢您的回答.. 我知道如何在 c++ 中正确转换 >> 但我不知道如何在 c 中进行再次感谢
【解决方案2】:

对于这个简单的任务,使用

双a,b;
if (fscanf(myfile, "%lf %lf", &a, &b) == 2)
        printf("%f + %f = %f\n", a, b, a+b);
.

【讨论】:

    【解决方案3】:

    看起来像一个家庭作业问题,但fscanf 可以将字符串读入如下变量:

    int n;
    fscanf (myfile,"%d",&n); 
    

    【讨论】:

    • 不,这不是作业...我正在尝试计算从电影中提取的帧之间的时间差...
    • 由于某些数字似乎是小数,%d 格式和int 类型可能不是最佳匹配。
    【解决方案4】:

    你没有显示你需要什么作为单值行的输出,但这看起来像 fgets()sscanf() 的情况,除非你真的希望将具有单个值的两行处理为一个单位。

    char buffer[256];
    int rownum = 0;
    while (fgets(buffer, sizeof(buffer), myfile) != 0)
    {
        double aa, bb;
        int n = sscanf(buffer, "%lf %lf", &aa, &bb);
        if (n == 2)
            printf("%d Pair:(%g, %g) = %g\n", ++rownum, aa, bb, aa+bb);
        else if (n == 1)
            printf("%d Solo:(%g) = %g\n", ++rownum, aa, aa);
        else
        {
            printf("Failed to find any numbers in <<%s>>\n", buffer);
        }
    }
    

    如果您使用fscanf(myfile, "%g %g", &amp;aa, &amp;bb),那么它将读取换行符(它们被视为空格)以查找数字,因此它会从一行读取一个数字,然后从另一行读取第二个。这通常不是人们所追求的(但当你需要它时,它非常有用)。使用fscanf() 进行错误恢复往往比使用fgets()sscanf() 更令人担忧。

    【讨论】:

      【解决方案5】:

      它在 c++ 中对不起:(我不知道 c

      这是一个非常简单的逻辑代码,用于简单的头脑:我也是初学者,我还没有测试过这个程序,如果出现问题,很抱歉,但完全正确 我的解析器以同样的原则工作,它工作得很好。所以这是一个真正的方法。不是很有效,但是... 不要马上使用这个程序,了解它的逻辑这将对你有很大帮助。复制不会给你任何东西 ...解析器导师是如此罕见....

      int x=0; 字符 ch = 'r'; //我已经使用这个等式来避免第一次 ckeck 的错误。 它必须在程序启动时被填充。 字符比奇[10]; int checknumber = 0;

      float firstnumber = 0; 浮动秒数 = 0; 浮动结果=0;

      void clearar(char frombigar[10], int xar) //这个函数获取 bigch 作为引用,这意味着 eny 这里所做的更改,将直接影响 bigch 本身。 ths 函数获取数组的实际长度并放置空格 在 bigch 的每个元素中将数字归零。我们需要清除 以前任何数字的大人物。在下面你会明白为什么我需要这个。 'xar' 是来自主函数的 x。它在这里告诉我们的清洁工 填充的 bigar 元素的真实长度。 { 对于 (int i=0; 我 }

      }

      int main() {

       if (ch!= "  ")                   //i used space as an indicator where one number ends
                                        //so while space havent been reahced, read letters.
          { bigch[x] = ch;              //get read letter into bigch array. 
            x++;                        //icrement bigch array step
      
          }
       else 
      
       if(ch == " ")             //if space is reached that means one number has ended and
        {                        im trying to set a flag at that moment. it will be used further.
          checknumber++;         the flag is simple number. first space will set checknumber to 1
                                 second space will set it to 2. thats all.
        } 
      
        if (checknumber == 1)                      //if our checknumber is 1, wich means that reading  
                                                   of first number is done, lets make one whole float              
                                                   from that bigch array.
      

      { firstnumber = atof(bigch); //这里我们得到bigch,atof(数组到浮点数)命令转换 bigch 数组转换为一个整数浮点数。

         clearar(bigch,x);                             //here we send bigch and its element step into function where  
                                                       bigch gets cleaned because we dont want some ghost numbers in it.
                                                       abviously clearar function cleans bigch int main function aswell, 
                                                        not only in it's teritory. its a global cleaning :)
               }
          else if (checknumber ==2)                     //here we do the same but if flag is 2 this means that two spaces
                                                        had been passed and its time to convert bigch into secondnumber.
                  { secondnumber = atof(bigch);          //same method of converting array into float (it hates other
                                                         not number letters, i mean if its a number its fine. if in your text
                                                         was 'a' or 's' in that case atof will panic hehe.. )
                   clearar(bigch,x);                     //same thing, we send bigch to cleaner function to kill any numbers 
                                                          it, we get one space letter ( " " ) into each element of bigch.
                  }
      

      校验码 = 0;如果两个数字都被读出并转换。我们需要重置 空间标志。并从0开始计数;下一对号码。

      结果=第一个数字+第二个数字;那么这里一切都清楚了。 } }

      【讨论】:

        猜你喜欢
        • 2022-12-10
        • 2020-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多