我试图读取一个文本文件并提取“X”的坐标,这样我就可以将文本文件放置在地图上
10 20
9 8 X
2 3 P
4 5 G
5 6 X
7 8 X
12 13 X
14 15 X我尝试过多次,但是我无法提取相关的数据并将其放在单独的变量中来绘制,我对c非常陌生,并且正在尝试学习一些东西,因此我们非常感谢您的帮助。
提前感谢
发布于 2022-10-11 18:21:35
从我最重要的评论,我建议了一系列的点结构。
下面是重构的代码。
我将scanf更改为使用%s而不是%c作为点名。它概括了点名,并可能在输入行中更好地工作,因为我认为%c不能正确匹配。
它编译但未经测试:
#include <stdio.h>
#include <stdlib.h>
struct point {
int x;
int y;
char name[8];
};
struct point *points;
int count;
int map_row;
int map_col;
void
read_data(const char *file_name)
{
FILE *fp = fopen(file_name, "r");
if (fp == NULL) {
/* if the file opened is empty or has any issues, then show the error */
perror("File Error");
return;
}
/* get the dimensions from the file */
fscanf(fp, "%d %d", &map_row, &map_col);
map_row = map_row + 2;
map_col = map_col + 2;
while (1) {
// enlarge dynamic array
++count;
points = realloc(points,sizeof(*points) * count);
// point to place to store data
struct point *cur = &points[count - 1];
if (fscanf(fp, "%d %d %s", &cur->x, &cur->y, cur->name) != 3)
break;
}
// trim to amount used
--count;
points = realloc(points,sizeof(*points) * count);
fclose(fp);
}发布于 2022-10-11 18:41:17
有很多方法可以解决这个问题。克雷格在使用struct来协调不同类型的数据方面有一些非常好的地方。这种方法使用fgets()进行读取,并使用sscanf()解析所需的数据。这样做的好处是消除了匹配失败的风险,使输入流中的字符未被读取,这将从匹配失败的角度破坏其余的读取。使用fgets()读取时,您一次要消耗一行输入,而这种读取与使用sscanf()解析值无关。
总之,允许由程序的第一个参数提供文件名(如果没有提供参数,默认情况下从stdin读取),您可以这样做:
#include <stdio.h>
#define MAXC 1024 /* if you need a constand, #define one (or more) */
int main (int argc, char **argv) {
char buf[MAXC]; /* buffer to hold each line */
int map_row, map_col; /* map row/col variables */
/* use filename provided as 1st argument (stdin if none provided) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
perror ("file open");
return 1;
}
/* read/validate first line saving into map_row, map_col */
if (!fgets (buf, MAXC, fp) ||
sscanf (buf, "%d %d", &map_row, &map_col) != 2) {
fputs ("error: EOF or invalid map row/col data.\n", stderr);
return 1;
}
/* loop reading remaining lines, for used as line counter */
for (size_t i = 2; fgets (buf, MAXC, fp); i++) {
char suffix;
int x, y;
/* validate parsing x, y, suffix from buf */
if (sscanf (buf, "%d %d %c", &x, &y, &suffix) != 3) {
fprintf (stderr, "error: invalid format line %zu.\n", i);
continue;
}
if (suffix == 'X') { /* check if line suffix is 'X' */
printf ("%2d %2d %c\n", x, y, suffix);
}
}
if (fp != stdin) { /* close file if not stdin */
fclose (fp);
}
}(注意:--这仅仅说明了从带有'X'后缀的行中读取和隔离值。数据处理和计算留待您处理)
示例使用/输出
使用dat/coordinates.txt中的数据,您可以:
$ ./bin/readcoordinates dat/coordinates.txt
9 8 X
5 6 X
7 8 X
12 13 X
14 15 X正如Craig所指出的,如果您需要存储匹配的数据,那么struct数组提供了一个很好的解决方案。
https://stackoverflow.com/questions/74032142
复制相似问题