I need to write C program that reads from file the car number, miles driven, and gallons used. Calculate the miles per gallon. Calculate the totals and the average MPG.
I only need help with counting miles per gallon.
In output should be :20 But my output is: 1966018914
25 20
24 25
23 24
Can anyone see my code and help me figure it out?!
Here is code:
int main()
{
int car, miles, gas;
int sumMiles = 0;
int sumGas = 0;
int avgMPG = 0;
FILE *inFile, *outFile;
char fname[20];
printf("Enter a file name: ");
gets(fname);
inFile = fopen(fname, "r");
if (inFile == NULL)
{
printf("\nFailed to open file.\n");
exit(1);
}
outFile = fopen("output.txt","w");
if(outFile==NULL)
{
printf("The file was not opened.");
exit(1);
}
printf("\nCar No. Miles Driven Gallons Used\n");
while (fscanf(inFile, "%d %d %d",&car, &miles, &gas) != EOF)
{
printf("%-7d %-15d %d\n",car,miles,gas);
sumMiles += miles;
sumGas += gas;
avgMPG = sumMiles / sumGas;
}
printf("\nThe total miles driven is %d\n", sumMiles);
printf("The total gallons of gas used is %d\n", sumGas);
printf("The average miles per gallon of gas used is %d\n", avgMPG);
printf("File copied succesfully!");
fclose(inFile);
fclose(outFile);
}
This is input file:
123 100 5
345 150 6
678 240 10
901 350 15
Your program is working just fine: IdeOne demo.
All I did to your code is to remove input and output files and replace them with stdin and stdout which is required by IdeOne. Also, you do not seem to use output file anywhere.
Input:
123 100 5
345 150 6
678 240 10
901 350 15
Output:
Car No. Miles Driven Gallons Used
123 100 5
345 150 6
678 240 10
901 350 15
The total miles driven is 840
The total gallons of gas used is 36
The average miles per gallon of gas used is 23
Your code works with everyone else but you. The issue may be in the environment then. Do you have an exotic encoding in your text editor? Are you leaving stray characters, indentation etc?
Your code is working fine. You have been using printf in code which will not work it want to write output to a file you need to use fprint.
Please have a look at below code which works as you need.
int main()
{
int car, miles, gas;
int sumMiles = 0;
int sumGas = 0;
int avgMPG = 0;
float ans=0;
FILE *inFile, *outFile;
char fname[20];
printf("Enter a file name: ");
gets(fname);
inFile = fopen(fname, "r");
if (inFile == NULL)
{
printf("\nFailed to open file.\n");
exit(1);
}
outFile = fopen("output.txt","w");
if(outFile==NULL)
{
printf("The file was not opened.");
exit(1);
}
while (fscanf(inFile, "%d %d %d",&car, &miles, &gas) != EOF)
{
sumMiles += miles; // not needed acc to output
sumGas += gas; // not needed acc to output
avgMPG = sumMiles / sumGas; // not needed acc to output
ans = miles/gas;
fprintf(outFile,"%f\n",ans);
}
fclose(inFile);
fclose(outFile);
}
Related
When I go to run this within my terminal it will simply tell me it is a segmentation fault. This program reads in a file called DATA. This is a txt file that contains exam scores. The scores go as following (if at all relevant): 10 25 50 50 5 0 0 45 45 15 25 50 2 50 30 40.
#include <stdio.h>
int main()
{
FILE *fp = fopen("DATA", "r"); //Opens the file DATA in read mode.
int possibleScoreCounts[51] = {0};
int score;
while(!feof(fp))
{
fscanf(fp, "%d", &score);
possibleScoreCounts[score]++;
}
printf("Enter a score to check on the exam: ");
scanf("%d", &score);
while(score != -1)
{
int count = 0;
for(int i = 0; i < score; i++)
count = count + possibleScoreCounts[i];
printf("%d scored lower than %d\n", count, score);
printf("Enter a score to check on the exam: ");
scanf("%d", &score);
}
}
your code compiles under c99 to compile it with out move i declatration outside the for
I tested this on my system and it works (as far as logic goes)
This means that one of the specific functions fopen, fscanf, or scanf failes - you must check error values
EDIT: New Problem, now I get a totally different output than the one I need. The following is how I have it written, assignment instruction is on the bottom, please and thank you all!
#include<stdio.h>
#include<stdlib.h>
int main() {
FILE * ifp = NULL;
char filename[20];
printf("What is the name of the input file?\n");
scanf(" %s", &filename);
while (ifp == NULL){
/*PROMPT USER FOR INPUT FILENAME*/
printf("What is the name of the input file?\n");
scanf(" %s", &filename);
/*OPEN INPUT FILE*/
ifp = fopen(filename, "r");
}
int totalSize = 0;
fscanf(ifp, "%d", &totalSize);
int id[totalSize];
char category[totalSize];
int handCombatPt[totalSize];
int distCombatPt[totalSize];
int observationPt[totalSize];
int concealPt[totalSize];
int agilityPt[totalSize];
float ranking[totalSize];
int row=0;
for (row=0; row<totalSize; row++) {
fscanf(ifp, "%d %c %d %d %d %d %d\n", id+row, category+row, handCombatPt+row, distCombatPt+row, observationPt+row, concealPt+row, agilityPt+row);
}
for (row=0; row<totalSize; row++) {
if (category[row] == 'A') {
ranking[row] = (handCombatPt[row] + distCombatPt[row]*2 + observationPt[row]*2 + concealPt[row] + agilityPt[row]*5)/10.0;
}
if (category[row] == 'C') {
ranking[row] = (handCombatPt[row]*5 + distCombatPt[row]*5 + observationPt[row] + concealPt[row] + agilityPt[row]*2)/10.0;
}
if (category[row] == 'S') {
ranking[row] = (handCombatPt[row] + distCombatPt[row] + observationPt[row]*5 + concealPt[row]*5 + agilityPt[row]*2)/10.0;
}
}
int firstA, firstS, secondS, firstC, secondC;
for (row=0; row<totalSize; row++) {
if (category[row]=='A' && ranking[firstA] < ranking[row]) {
firstA = row;
}
if (category[row]=='S' && ranking[firstS] < ranking[row]) {
secondS = firstS;
firstS = row;
}
else if (category[row]=='S' && ranking[secondS] < ranking[row]) {
secondS = row;
}
if (category[row]=='C' && ranking[firstC] < ranking[row]) {
secondC = firstC;
firstC = row;
}
else if (category[row]=='C' && ranking[secondC] < ranking[row]) {
secondC = row;
}
}
printf("A : %d %f \n", id[firstA], ranking[firstA]);
printf("C : %d %f \n", id[firstC], ranking[firstC]);
printf("C : %d %f \n", id[secondC], ranking[secondC]);
printf("S : %d %f \n", id[firstS], ranking[firstS]);
printf("S : %d %f \n", id[secondS], ranking[secondS]);
return 0;
}
And here's the input.txt file:
10
14 A 447 252 68 34 978
2 C 230 299 597 180 9
27 A 318 220 97 28 1317
32 C 563 450 547 112 28
8 C 669 260 200 36 171
11 S 179 45 1342 732 174
19 S 74 249 861 1165 6
21 A 757 240 97 119 2032
15 S 275 177 588 577 52
6 C 886 401 327 109 48
The program needs to output the follow:
A: 21 1171.00
C: 6 696.70
C: 32 578.00
S: 11 1094.20
S: 19 1046.50
Any help would be greatly appreciated!
EDIT: Here is the assignment in case it helps anyone understand what I'm trying to do
Problem: Mentorship
It is time for your friend to select their ninja mentors! Ninja students are able to select several mentorsfrom the class of higher level students to learn special skills from. Skills are categorized as Stealth (S),Combat (C), and Agility (A). Your friend will be provided with a file of older students that has their nameand rankings for the different skills. They can then choose 5 mentors to learn from. To assist, your program should read in all of the student’s information and print out the two bestcombat mentors, the two best stealth mentors, and the best agility mentor. If your friend has been adiligent student, they will be able to select these best options! If not, they will need to go down the listand select other mentors.Combat Skills are split into Hand to Hand and Distance. Stealth skills are split into Observation andConcealment. Agility is a singular category.
Input File Format
The first line of the input file will contain a single integer n (5 ≤ n ≤ 100), denoting the number ofpotential mentors, for which information is listed in the file. The following n lines will have all theinformation for all the mentors with one mentor's information on a single line. Each line will have thefollowing format:ID Category HandCombatPts DistanceCombatPts ObservationPts ConcealPts AgilityPtsID will be a positive integer representing the potential mentor.
Category will be a single character, either 'C', 'S' or 'A', for combat, stealth or agility, respectively.HandCombatPts will be an integer representing the number of points that student was given last year bytheir hand to hand combat instructor. DistanceCombatPts will be an integer representing the number of points that student was given lastyear by their distance combat instructor.ObservationPts will be an integer representing the number of points that student was given last year by
their observation and spying skills instructor.
ConcealPts will be an integer representing the number of points that student was given last year by their
concealment and disguise instructor.
AgilityPts will be an integer representing the number of points that student was given last year by theiragility and acrobatics instructor.
How to Compute a Ranking
For each potential mentor, their ranking will be a summation weighted by their category. If they are a potential combat mentor their ranking should be:(HandCombatPts*5 + DistanceCombatPts*5 + ObservationPts + ConcealPts + AgilityPts*2)/10If they are a potential stealth mentor their ranking should be:(HandCombatPts + DistanceCombatPts + ObservationPts*5 + ConcealPts*5 + AgilityPts*2)/10If they are a potential agility mentor their ranking should be:(HandCombatPts + DistanceCombatPts*2 + ObservationPts*2 + ConcealPts + AgilityPts*5)/10
Program Specification
You must use arrays to solve the problem.
Your program should first prompt the user for the name of the input file. Then, your programshould process the input file and write the five best mentors for your friend. Each line shouldlist the category, the ID, and the ranking of the mentor, respectively, separated by spaces.Round the ranking to two decimal places. The mentors must be listed according to category asfollows: agility, followed by the two combat, followed by the two stealth. Both the combat andthe stealth mentors must be listed in descending order of ranking.
First:
'Program compiles but then “program.exe has stopped working'
I'm sorry to have to inform you that this is the usual behaviour. Writing code and getting it to compile is trivial compared with the effort and skill required to get it to do what you want. Testing and debugging is 99% of software development skill. That is why debuggers exist.
Next:
ALWAYS check the result of ALL system calls. In your case, specifically fopen().
...............
[sigh] 'after I set the uninitialized variables to 0, but now I get a completely different output then the one I need'
See above, especially the hint: 'That is why debuggers exist'. It is really MUCH easier for you to fix your problems than to use SO contributors remote-debug by text exchange. You have the actual code, (ie. not what you originally posetd), the environment, test files etc. We have what you are drip-feeding us, both in terms of what you are doing and what you are getting:(
You must learn to debug now, before you write even one more line of code. If you cannot debug, you cannot develop programs and should not try:(
#include<stdio.h>
#include<stdlib.h>
int main() {
FILE * ifp = NULL;
char filename[20];
while (ifp == NULL){
printf("What is the name of the input file?\n");
scanf(" %s", &filename);
ifp = fopen(filename, "r");
}
int totalSize = 0;
fscanf(ifp, "%d", &totalSize);
int id[totalSize];
char category[totalSize];
int handCombatPt[totalSize];
int distCombatPt[totalSize];
int observationPt[totalSize];
int concealPt[totalSize];
int agilityPt[totalSize];
float ranking[totalSize];
int row=0;
for (row=0; row<totalSize; row++) {
fscanf(ifp, "%d %c %d %d %d %d %d\n", id+row, category+row, handCombatPt+row, distCombatPt+row, observationPt+row, concealPt+row, agilityPt+row);
}
for (row=0; row<totalSize; row++) {
if (category[row] == 'A') {
ranking[row] = (handCombatPt[row] + distCombatPt[row]*2 + observationPt[row]*2 + concealPt[row] + agilityPt[row]*5)/10.0;
}
if (category[row] == 'C') {
ranking[row] = (handCombatPt[row]*5 + distCombatPt[row]*5 + observationPt[row] + concealPt[row] + agilityPt[row]*2)/10.0;
}
if (category[row] == 'S') {
ranking[row] = (handCombatPt[row] + distCombatPt[row] + observationPt[row]*5 + concealPt[row]*5 + agilityPt[row]*2)/10.0;
}
}
int firstA=0, firstS=0, secondS=0, firstC=0, secondC=0;
for (row=0; row<totalSize; row++) {
if (category[row]=='A' && ranking[firstA] < ranking[row]) {
firstA = row;
}
if (category[row]=='S' && ranking[firstS] < ranking[row]) {
secondS = firstS;
firstS = row;
}
else if (category[row]=='S' && ranking[secondS] < ranking[row]) {
secondS = row;
}
if (category[row]=='C' && ranking[firstC] < ranking[row]) {
secondC = firstC;
firstC = row;
}
else if (category[row]=='C' && ranking[secondC] < ranking[row]) {
secondC = row;
}
}
printf("A : %d %f \n", id[firstA], ranking[firstA]);
printf("C : %d %f \n", id[firstC], ranking[firstC]);
printf("C : %d %f \n", id[secondC], ranking[secondC]);
printf("S : %d %f \n", id[firstS], ranking[firstS]);
printf("S : %d %f \n", id[secondS], ranking[secondS]);
return 0;
}
This worked, I initialized everything to 0 and made a while loop for the file name, now it outputs corerctly, though more numbers after the decimal than I need but I think i can fix it with a .lf in the variable print part. If anyone can check that and let me know if they see any thing wrong with it please. Thank you all for the help!
I have this assignment that I can't figure out.
We have a file in the following format:
5
4
100 500 250 300
1
700
3
300 150 175
2
920 680
8
20 10 15 25 50 30 19 23
On the first line we have the total number of auctions.
Afterwards, each two rows represent an auction.
On the first row there is the number of bids. On the following row there are the actual bids.
For example the number 4 describes an auction with 4 bids (100,500,250,300).
My task is to determine the highest bid for each auction. This is what I've got so far. Any help will be appreciated.
#include <stdio.h>
int main() {
FILE * ifp;
char filename[100];
printf("File name\n");
scanf("%s", &filename);
ifp = fopen (filename, "r");
if (ifp == NULL) {
printf("Error, File could not be opened.\n");
return 1;
}
int i, num_auctions, auction, j, bid, max;
fscanf(ifp, "%d", &num_auctions);
for(i=0; i<num_auctions; i++) {
fscanf(ifp, "%d", &auction);
if (bid > max)
max = bid;
for(j=0; j<auction; j++){
fscanf(ifp, "%d", &bid);
printf("%d\n", bid);
}
printf("%d\n", max);
}
fclose(ifp);
return 0;
}
These are the problems in your code.
bid and max are used unintialised. Fix is to set them to 0 when they are declared.
The if (bid > max) check is in the wrong spot. It's only checking the last bid of each auction. The fix is to move that check into the inner for loop after the fscanf.
max needs to be cleared after each auction. The fix is to set max to 0 at the top of the outer for loop.
Following code is meant to read values and save them to an array. Just that when I build and run my code my file isn't found. I'm basically trying to make a program that takes a data point from a file and inputting it into my code. When it runs it shows that the file isn't found though correctly inputting the file name.
#include <stdio.h>
#include <stdlib.h>
//function prototype
void calc_results(int time[], int size);
void read_temps(int temp[]);
//set size of array as global value
#define SIZE 25
int main ()
{
rand();
//Declare temperature array with size 25 since we are going from 0 to 24
int i, temp[SIZE];
read_temps(temp);
//Temperature for the day of October 14, 2015
printf("Temperature conditions on October 14, 2015:\n");
printf("\nTime of day\tTemperature in degrees F\n\n");
for (i = 0; i < SIZE; i++)
printf( "%d \t\t%d\n",i,temp[i]);
//call the metod calc_results(temp, SIZE);
calc_results(temp, SIZE);
//pause the program output on console until user enters a key
system ("PAUSE"); return 0;
}
/**The method read_temps that takes the input array temp
and prompt user to enter the name of the input file
"input.txt" and then reads the tempertures from the file
for 24 hours of day */
void read_temps(int temp[])
{
char fileName[50];
int temperature;
int counter=0;
printf("Enter input file name : ");
//prompt for file name
scanf("%s",fileName);
//open the input file
FILE *fp=fopen(fileName, "r");
//check if file exists or not
if(!fp)
{
printf("File doesnot exist.\n");
system ("PAUSE"); //if not exit, close the program
exit(0);
}
//read temperatures from the file input.txt until end of file is encountered
while(fscanf(fp,"%d",&temperature)!=EOF)
{
//store the values in the temp array
temp[counter]=temperature;
//incremnt the coutner by one
counter++;
}
//close the input file stream fp
fclose(fp);
}
void calc_results(int temp[], int size)
{
int i, min, max, sum = 0;
float avg;
min = temp[0];
max = temp[0];
//Loop that calculates min,max, sum of array
for (i = 0; i < size; i++)
{
if (temp[i] < min)
{
min = temp[i];
}
if (temp[i] > max)
{
max = temp[i];
}
sum = sum + temp[i];
}
avg = (float) sum / size;
//open an external output file
FILE *fout=fopen("output.txt","w");
//Temperature for the day of October 14, 2015
fprintf(fout,"Temperature conditions on October 14, 2015:\n");
fprintf(fout,"\nTime of day\tTemperature in degrees F\n\n");
//write time of day and temperature
for (i = 0; i < SIZE; i++)
{
fprintf( fout,"%d \t\t%d\n",i,temp[i]);
}
printf("\nMin Temperature for the day is : %d\n", min);
printf("Max Temperature for the day is :%d\n", max);
printf("Average Temperature for the day is : %f\n", avg);
//write min ,max and avg to the file "output.txt"
fprintf(fout,"\nMin Temperature for the day is : %d\n", min);
fprintf(fout,"Max Temperature for the day is :%d\n", max);
fprintf(fout,"Average Temperature for the day is : %f\n", avg);
//close the output file stream
fclose(fout);
}
so i got the whole setup for my program and i was able to read the whole file content. the only one thing i need is to be able to add each column and put it in the variables i made. first column is miles second is gallons. so how can i make it possible using my code.
54 250 19
62 525 38
71 123 6
85 1322 86
97 235 14
#include <stdio.h>
#include <conio.h>
int main()
{
// pointer file
FILE *pFile;
char line[128];
int miles;
int gallons;
int mpg;
// opening name of file with mode
pFile = fopen("Carpgm.txt","r");
//headers
printf("Car No. Miles Driven Gallons Used\n");
//checking if file is real and got right path
if (pFile != NULL)
{
while (fgets(line, sizeof(line), pFile) != NULL)
{
int a, b, c;
if (sscanf(line, "%d %d %d", &a, &b, &c) == 3)
{
/* Values read */
printf("%d %d %d\n",a, b, c);
}
}
mpg = miles / gallons;
printf("Total miles driven: \n",miles);
printf("Total Gallons of gas: \n",gallons);
printf("Average MPG: \n",mpg);
printf("%d",a);
//closing file
fclose(pFile);
}
else
{
printf("Could not open file\n");
}
getch();
return 0;
}
That depends what you want to do.
If you just want to add values, you can do something like:
...
int miles = 0;
int gallons = 0;
...
/* Values read */
miles += b;
gallons += c;
...
Note that you can't print a like you did before closing the file as a is defined only in the while loop.
Furthermore, your printf statements won't work as expected, you forgot to specify the format %d, do:
printf("Total miles driven: %d\n",miles);
printf("Total Gallons of gas: %d\n",gallons);
printf("Average MPG: %d\n",mpg);