gpt4 book ai didi

c - 将文件中特定点的数字存储为 (x, y) 坐标

转载 作者:行者123 更新时间:2023-11-30 15:03:50 25 4
gpt4 key购买 nike

我有一个Instance File我需要以二维数组系统的形式存储NUM_PT和所有相应的坐标(个人选择,以便我可以轻松访问它们 )。我能够检索 NUM_PT,但我无法将连续的坐标读入数组。

这就是我所做的

/* Assignment 2 */

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



#define MAXS 256

int main(int argc, char *argv[])

{

int num_pt;
int inputfile = 0, outputfile = 0, i;

for (i = 1; i < argc; i++)
{
if (strcmp (argv[i], "-i") == 0)
inputfile = i+1;
if (strcmp (argv[i], "-o") == 0)
outputfile = i+1;
}
if (inputfile == 0)
{
/* invalid command line options */
printf("\nIncorrect command-line...\n");
printf("> %s [-i inputfile [-o outputfile]]\n\n", argv[0]);
exit(0);
}

FILE *fp;
fp = fopen(argv[inputfile], "r");

int count = 0;
if (fp == 0)
{
printf("\nCould not find %s\n", argv[inputfile]);
exit(0);
}

char line[MAXS];
while (fgets(line, sizeof line, fp) != NULL)
{
if (count == 4)
{
fscanf(fp, "%d", &num_pt);
break;
}
else
count++;

}

int arr[num_pt][1];
while (fgets(line, sizeof line, fp) != NULL)
{
if (count == 5)
{
int k, j, cord;
for (k = 0; k < num_pt; k++)
{
for (j = 0; j < num_pt; j++)
{
while (fscanf(fp, "%d%d", &cord) > 0)
{
arr[k][j] = cord;
j++;
}
}
}
}
}
fclose(fp)
return 0;

}

检索NUM_PT后,我尝试重新初始化count更改为 5,因为坐标从文件中的 **LINE 6* 开始。

编译器错误 ubuntu bash script

语言:c99 ;编译器:gcc

最佳答案

“将数字存储为文件中的 (x, y) 坐标”示例(最好不要固定读取位置)

#include <stdio.h>

typedef struct point {
int x, y;
} Point;

int readPoint(FILE *fp, Point *p);
int readInt(FILE *fp, int *n);

int main(void){
FILE *fp = fopen("instance10_001.txt", "r");
Point p;
int MAX_X, MAX_Y;

readPoint(fp, &p);
MAX_X = p.x;
MAX_Y = p.y;
printf("MAX_X:%d, MAX_Y:%d\n", MAX_X, MAX_Y);

int NUM_PT;
readInt(fp, &NUM_PT);
printf("NUM_PT:%d\n", NUM_PT);

Point arr[NUM_PT];
for(int i = 0; i < NUM_PT; ++i){
readPoint(fp, &arr[i]);
printf("Point(%d, %d)\n", arr[i].x, arr[i].y);
}
fclose(fp);
}

int readLine(FILE *fp, char *buff, int buff_size){
while(fgets(buff, buff_size, fp)){
if(*buff == '#' || *buff == '\n')
continue;
return 1;
}
return 0;
}

#define LINE_MAX 128
int readPoint(FILE *fp, Point *p){
char buff[LINE_MAX];
if(readLine(fp, buff, sizeof buff)){
return 2 == sscanf(buff, "%d %d", &p->x, &p->y);
}
return 0;
}
int readInt(FILE *fp, int *n){
char buff[LINE_MAX];
if(readLine(fp, buff, sizeof buff)){
return 1 == sscanf(buff, "%d", n);
}
return 0;
}

关于c - 将文件中特定点的数字存储为 (x, y) 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40538064/

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