gpt4 book ai didi

c - 如何将 .txt 文件中的值读取到 C 程序中

转载 作者:行者123 更新时间:2023-11-30 15:20:57 26 4
gpt4 key购买 nike

我在将 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 文件, 例如./program

最佳答案

scanf and family返回一个值,告诉您它成功扫描了多少个值:

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 进行标记并循环读取值。

关于c - 如何将 .txt 文件中的值读取到 C 程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29763269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com