如何将 .txt 文件中的值读入 C 中的程序

How to read values from a .txt file into a program in C

我无法将 txt 文件中的值读入我的程序。我给出的值是坐标 (x,y) 后跟 2 个空格。假设最大点数为 100,那么我如何读取输入以便我的程序每行只读取给定数量的值?到目前为止,我的程序旨在计算两点之间的距离并使用总和求周长。

3 12867 1.0 2.0  1.0 5.0  4.0 5.0  
5 15643 1.0 2.0  4.0 5.0  7.8 3.5  5.0 0.4  1.0 0.4

到目前为止我能想到的是:

scanf("%f %f %f %f %f %f", &x1, &y1, &x2, &y2, &x3, &y3);

到目前为止,这也是我的程序。

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

#define MAX_PTS 100
#define MAX_POLYS 100
#define END_INPUT 0

struct Point {
    double x, y;
};

double getDistance(struct Point a, struct Point b) {
    double distance;
    distance = sqrt((a.x - b.x) * (a.x - b.x) + (a.y-b.y) *(a.y-b.y));
    return distance;
}

int main(int argc, char *argv[]) {
    int npoints, poly_id;
    struct Point a, b;

    if(scanf("%d %d", &npoints, &poly_id)) {
        scanf("%lf %lf", &a.x, &a.y);
        scanf("%lf %lf", &b.x, &b.y);
    } else { printf("\nUnable to read input.\n");
      exit(EXIT_FAILURE);
    }

    printf("\nStage 1\n=======\n");
    printf("First polygon is %d\n", poly_id);
    printf("   x_val   y_val\n    %1.1f     %1.1f\n    %1.1f     %1.1f\n",
    a.x, a.y, b.x, b.y);
    printf("perimeter = %2.2lf m\n", getDistance(a, b));


    return 0;
}

输出为:

First polygon is 12867
   x_val   y_val
    1.0     2.0
    1.0     5.0
perimeter = 3.00 m

编辑:我必须补充一点,必须使用重定向来读取 txt 文件, 例如./程序 < txt 文件

关于你的方法

要从文件中读取数据,您需要 fscanf() 函数。在此处阅读 man page

注意:如果你想使用fscanf()强烈建议你检查return相同的值以确保正确输入。

关于值的存储,您可以使用以下任何一种方法

替代方法:

更好的方法是

  1. 使用fgets()阅读整个
  2. 使用 strtok() 对输入进行标记。
  3. 使用strtof()
  4. 字符串转换为浮点数
  5. continue until NULL from strtok(),表示完成读取 line.
  6. 中的所有值
  7. 继续直到 fgets() return NULL 标记所有数据已从文件中读取。

P.S - 我希望您已经了解使用 fopen()/ fclose().

的文件打开/关闭操作

scanf and family return 一个告诉您它成功扫描了多少个值的值:

RETURN VALUE

  These functions return the number of input items successfully matched
   and assigned, which can be fewer than provided for, or even zero in
   the event of an early matching failure.

因此,只要您知道最大点数,您仍然可以使用scanf。这是 sample program:

#include <stdio.h>
void read(char *line) {
    float x1 = 0, x2 = 0;
    int n = sscanf(line, "%f %f", &x1, &x2);
    printf("Read %d, %f %f\n", n, x1, x2);
}
int main(void) {
    char *line1 = "1.0";
    char *line2 = "1.0 2.0";
    read(line1);
    read(line2);
    return 0;
}

输出:

Read 1, 1.000000 0.000000
Read 2, 1.000000 2.000000

但是,从事物的声音来看,100 是很多数字,因此您可以尝试使用 strtok 进行标记化并循环读取值。

从我在你的点示例中看到的情况来看,你对点进行了特定的分隔,即制表符和换行符。我的建议如下:

  1. 编写一个遍历 TXT 文件中每个字符的循环
  2. 一旦检测到数字字符,就会激活一个新状态(一种方法),您可以在该状态(一种方法)中开始检测一个点,直到一个制表符(“\t”)或一个新行(“\n” ) 被检测到。因为你有一个固定的格式,你可以使用你的

    scanf("%f %f", &x1, &x2);
    

    当你检测到一个数字字符(我建议你使用一个点数组(因为你有固定数量的点)(一个点是一个以 x,y 作为其成员的结构)。你必须 return向后一个字符,以便检测点的完整坐标,因为您的点的第一个数字字符用于触发检测状态。

  3. 一旦检测到制表符或新行 return 进入循环并继续 "eating up" 制表符和新行直到下一个数字字符。

在您的示例中,解析可能如下所示:

  1. 打开文件进行读取并初始化 array/list 个点,设置计数器 := 0;
  2. 遍历字符(忽略制表符和换行符)直到到达 EOF 或计数器 == 100;
  3. 如果检测到数字字符解析坐标对(在此处使用您的 scanf());
  4. 向array/list添加点并增加计数器
  5. 转到 2;

希望这对您有所帮助。 :)

尝试以下代码片段:

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

int main()
{
   char ch, file_name[25];
   FILE *fp;
   int count=0;
   int i,j;
   int cordinate[5][5];

   fp = fopen('a.txt',"r"); // read mode

   if( fp == NULL )
   {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
   }

   while( ( ch = fgetc(fp) ) != EOF ){
      printf("%c",ch);
      for(i=0;i<5;i++)
      {
          for(j=0;j<5;j++){
               if(ch==' '){
          count++;
          cordinate[0][0]=
            }
         else{
          cordinate[i][j]=ch;
      }
      }
          }
      }
      printf('print content of file');
      for(i=0;i<5;i++)
      {
          for(j=0;j<5;j++){
              printf("cordinates:%d"+cordinate[i][j]);
          }
      }

   }

   fclose(fp);
   return 0;
}

在编程中,当他们想一次又一次地做一些事情时使用循环work

认为要计算多边形的参数,需要计算其边的长度。如果给定两个相邻点,您的函数 getDistance 可以找到边的长度。所以,你一直在寻找边的长度并添加它们。现在想想什么是重复workgetDistance 有新点。因此,请查看以下代码中的 for 循环。

我在代码中写了一些注释来说明这一点。

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

#define MAX_PTS 100
#define MAX_POLYS 100
#define END_INPUT 0

struct Point {
    double x, y;
};

double getDistance(struct Point a, struct Point b) {
    double distance;
    distance = sqrt((a.x - b.x) * (a.x - b.x) + (a.y-b.y) *(a.y-b.y));
    return distance;
}

int main(int argc, char *argv[]) {
    int npoints, poly_id;
    struct Point a, b;

    if(scanf("%d %d", &npoints, &poly_id)) {
        int iteration = 0;
        scanf("%lf %lf", &a.x, &a.y);
        struct Point initialPoint = a;
        double parimeter = 0;  // i start with 0 value of parimeter.     
        for (iteration = 1; iteration < npoints; ++iteration) {
            scanf("%lf %lf", &b.x, &b.y);  // take input for new-point.
            parimeter += getDistance(a, b); // add the parimeter.
       // for next iteration, new-point would be first-point in getDistance
            a = b; 
        }

        // now complete the polygon with last-edge joining the last-point
        // with initial-point.
        parimeter += getDistance(a, initialPoint);

        // print the information.
        printf("Polygon is %d\n", poly_id);
        printf("perimeter = %2.2lf m\n", parimeter); 
    } else { printf("\nUnable to read input.\n");
      exit(EXIT_FAILURE);
    }

    return 0;
}

查看实际代码:Working Code

注意我已经给了

输入:

 3 12867 1.0 2.0 1.0 5.0 4.0 5.0

输出为:

Polygon is 12867
perimeter = 10.24 m

现在,如果您想对更多多边形执行此操作work,希望您知道该怎么做!!!