我正在为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;
}
答案 0 :(得分:0)
我建议使用ofstream和ifstream:
我的代码在哪里说&#34; filename,&#34;替换为USACO问题陈述中给出的文件名。 fin
和fout
类似于cin
和cout
,但fin
和fout
读取并打印到输入/输出文件。
#include <fstream>
using namespace std;
ofstream fout("filename.out");
ifstream fin("filename.in");
int main()
{
int N;
fin >> N;
fout << N << endl;
}