I have a complete code worked out so that when I request user input, it works ju
ID: 3543951 • Letter: I
Question
I have a complete code worked out so that when I request user input, it works just fine. However, when I try to read from a separate .in file, I have a blank output. This may seem like a silly and unrealistic example, but for some reason, the code will not read from the file. The separate file is called dinosaur.in, meaning that it was created in notepad but sourced under all files instead of from a .txt file (the program must be able to read from a .in file). The program reads in a number of experiments in which the weight of a dinosaur egg is compared to the weight of a group of ostridge eggs. In the separate file, the first line represents the number of experiments, the second line represents the weight of the single dinosaur egg, the third line represents the number of ostridge eggs to be compared to the one dinosaur egg, and the fourth line represents the various weights of the ostridge eggs. This cycle will be repeated based on the number of experiments.The ostridge egg weights must all be on one line of the source file. Here is an example of a dinosaur.in test file:
2
90
4
15 20 30 30
120
3
25 27 18
The output would be:
Experiment #1: The ostridge eggs weigh more than the dinosaur egg!
Experiment #2: The dinosaur egg weighs more than the ostridge eggs!
Here is my code:
#include <stdio.h>
int main() {
FILE*ifp;
ifp = fopen("dinosaur.in", " r ");
int experiments, i;
fscanf(ifp, "%d", &experiments);
for (i=1; i<=experiments; i++) {
int dino_egg_weight, num_ost_eggs;
fscanf(ifp, "%d", &dino_egg_weight);
fscanf(ifp, "%d", &num_ost_eggs);
int total_egg_weight = 0, cnt =1;
while (cnt <= num_ost_eggs) {
int ost_egg_weight;
fscanf(ifp, "%d", &ost_egg_weight);
total_egg_weight = total_egg_weight+ost_egg_weight;
}
if (dino_egg_weight <=total_egg_weight)
printf("Experiment #%d: The ostridge eggs weigh more than the dinosaur egg! ", i);
else
printf("Experiment #%d: The dinosaur egg weighs more than the ostridge eggs! ", i);
}
fclose(ifp);
return 0;
}
Can someone please tell me why this code won't give an output from the dinosaur.in file? If there is a problem with my code, please let me know. Thank you so much!
Explanation / Answer
have you placed the file in the same folder as the source code?
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.