gpt4 book ai didi

c++ - 读取和写入 USACO 文件

转载 作者:行者123 更新时间:2023-11-30 20:32:33 25 4
gpt4 key购买 nike

我正在为 USACO 编写代码,但文件的读写不起作用。我正在尝试读取第一个文件行并将其存储为整数。后续行将被读取并存储到数组中以执行计算。我认为这个问题与 fopen 有关。我总是收到中止窗口,上面写着stream.valid()

这是代码_

__________________
// USACO MARATHON.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"


int main()
{
FILE *infp;
FILE *outfp;
int num_points = 0;
int x[] = { 0 };
int y[] = { 0 };
int total_dist = 0;
int i;
infp = fopen("C:\\Users\\jalen\\documents\\visual studio 2017\\Project\\real_marathon\\real_marathon\\Debug\\marathon.in", "r");
outfp = fopen("marathon.out", "w");
/*if ((infp = fopen("marathon.in", "r")) != NULL)
{
fscanf(infp, "%d", num_points);
}*/

num_points = fgetc(infp);

for (i = 0; i < num_points; i++)
{
fscanf(infp, "%d %d", &x[i], &y[i]);

}
for (i = 1; i < num_points; i++)
{
int total_distance = abs((x[i] - x[i - 1])) + abs((y[i] - y[i - 1]));
}
int max_skip = 0;
for (i = 1; i < num_points - 1; i++)
{
int dont_skip = abs((x[i + 1] - x[i])) + abs((x[i] - x[i - 1])) + abs((y[i + 1] - y[i])) + abs((y[i] - y[i - 1]));
int skip = abs((x[i + 1] - x[i - 1])) + abs((y[i + 1] - y[i - 1]));
int z = dont_skip - skip;
max_skip = z;
}
int output = total_dist - max_skip;
fprintf(outfp, "%d\n", output);
fclose(infp);
fclose(outfp);
return 0;
}

最佳答案

我建议使用 ofstream 和 ifstream:如果我的代码显示“文件名”,请替换为 USACO 问题陈述中给出的文件名。 finfoutcincout 类似,只是 fin >fout 读取并打印到输入/输出文件。

#include <fstream>

using namespace std;

ofstream fout("filename.out");
ifstream fin("filename.in");

int main()
{
int N;
fin >> N;
fout << N << endl;
}

关于c++ - 读取和写入 USACO 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47298434/

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