Error reading test cases from a file in C
for a programming homework, I'm implementing Prim's algorithm, the format of the input file for test cases is as follows:
The first line of input will be an integer C, which ind开发者_C百科icates the number of test cases. The first line of each test case contains two integers N and E, where N represents the number of nodes in the graph and E the number of edges, respectively. Then come E lines, each with 3 integers I, J and P, where I and J represent the nodes of an edge (undirected graphs, where 0 ≤ I, J
Although even I'm starting the code (I'm new to programming) i Don´t understand why my code only reads an entry for the test cases, What am I doing wrong?
this is the code reading the file entradaA.in:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv []){
int testCases;
int numberNodes;
int numberEdges;
freopen("entradaA.in", "r", stdin);
int i, j, cont=1;
int total = 0;
int a, b, c;
scanf ("%d", &testCases);
for (i=0; i<testCases; ++i)
{
scanf ("%d %d", &numberNodes, &numberEdges); //Number Nodes & Edges
for (i=0; i<numberEdges; i++)
{
scanf ("%d %d %d", &a,&b,&c);//
printf ("%d %d %d\n", a, b, c);
}
printf ("Caso %d: Total Weight %d\n", cont++, total);
}
return (0);
}
The input file (entradaA.in) look something like this
2
7 11
0 1 17
0 2 10
0 6 14
1 2 6
1 3 1
2 3 4
2 6 3
3 4 7
4 6 10
4 5 2
5 6 9
6 9
0 1 30
0 2 30
1 3 22
1 5 33
2 3 20
2 4 33
3 4 15
3 5 20
5 4 20
You have the loop variable i
modified inside the loop, which is generally unwanted. In this case, since i
looped to 11 (the number of edges), it caused your program to terminate since 11 is not smaller than 2 (the number of test cases in the input).
You could use temporary variable (if you are using C++, thank you aardvarkk):
for (int i=0; i<testCases; ++i)
{
scanf ("%d %d", &numberNodes, &numberEdges); //Number Nodes & Edges
for (int j=0; j<numberEdges; j++)
Note that the int j
could also be int i
, but I wouldn't recommend it. Just use a variable with another name would be clearer. Or if you are in C, just drop the two int
and use variables that are local to the function.
For more, you could read this.
Your code produced the following output on my machine. The only change I made was to declare the int
values i
, j
etc. before the freopen
call to make the code standard C.
0 1 17
0 2 10
0 6 14
1 2 6
1 3 1
2 3 4
2 6 3
3 4 7
4 6 10
4 5 2
5 6 9
Caso 1: Total Weight 0
It's definitely reading more than your test cases, so I'm not sure what the problem is?
精彩评论