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.
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!
Making a payroll assignment in my intro to C class and the objective is to read a text file and then output their pay information to a text file. I've received some incompatible pointer errors and CodeBlocks is only giving me an output file which contains a bunch of gibberish. I posted the text file below with my comments so you can understand what I'm doing with my code. Any help will do, appreciate it guys and gals.
2 (this is the number of employees)
5.50 (pay rate for employee 0)
10.00 (pay rate of employee 1)
3 (number of weeks)
2 (data in relation to this week)
1 10 30 13 30 (reads: employee 1 clocked in at 1030, clocked out 1330)
0 7 0 16 30 (reads: employee 0 clocked in at 700, clocked out 1630)
4
0 9 0 14 30
1 7 0 23 0
1 9 0 22 0
1 7 20 23 20
3
0 10 0 15 0
1 8 0 12 0
0 9 30 11 30
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define EMPLOYEES 20
#define WEEKS 10
/*prototype functions: One to take in the total hours, the other printing out the text file*/
double totalHrs(int hi, int mi, int ho, int mo);
void printLog( int weeks, int numEmp, double Emp[numEmp][2], int wkHrs[numEmp][weeks]);
int main()
{
/*variables for number of employees, number of weeks, shifts and hours in and hour along with minutes.*/
int n, weeks, shifts;
int empId, hrIn, minIn, hrOut, minOut, tmpWkHrs;
double m;
FILE *ifp;
/*Read clock text file*/
ifp = fopen("clock.txt", "r");
if(ifp == NULL)
{
exit(1);
}
/*scan in the number of employees*/
fscanf(ifp, "%d", &n);
if(n>EMPLOYEES)
{
printf("Employees provided is greater than 20");
exit(0);
}
double emp[n][2];
for(int i=0; i<n;i++)
{
fscanf(ifp, "%lf", &m);
emp[i][1] = m;
}
fscanf(ifp, "%d", &weeks);
double empWkHrs[n][weeks];
for(int i = 0; i < weeks; i++)
{
fscanf(ifp, "%d", &shifts);
for (int j = 0; j < shifts; j++)
{
fscanf(ifp, "%d", &empId);
fscanf(ifp, "%d", &hrIn);
fscanf(ifp, "%d", &minIn);
fscanf(ifp, "%d", &hrOut);
fscanf(ifp, "%d", &minOut);
emp[empId][0] += totalHrs(hrIn, minIn, hrOut, minOut);
empWkHrs[empId][i] += totalHrs(hrIn, minIn, hrOut, minOut);
}
}
printLog(weeks, n, emp, empWkHrs);
fclose(ifp);
return 0;
}
/*------------------------------------------------------------------------------------*/
double totalHrs(int hi, int mi, int ho, int mo)
{
double totalHrs = (double)abs(ho - hi);
double totalmins = (double)abs(mo - mi);
totalHrs += totalmins/60;
return totalHrs;
}
/*------------------------------------------------------------------------------------*/
/*Print function that prints out the information onto a text file named payroll*/
void printLog( int weeks, int numEmp, double Emp[numEmp][2], int wkHrs[numEmp][weeks])
{
FILE *ofp;
ofp = fopen("payroll.txt", "w+");
if(ofp == NULL)
{
exit(1);
}
fprintf(ofp, "Number of employees: %d\n", numEmp);
fprintf(ofp, "Number of weeks: %d\n", weeks);
/*Loop through to print out all of the information in regards to every week*/
for(int i = 0; i < weeks; i++)
{
fprintf(ofp, "Wk%d\n", weeks+1);
fprintf(ofp,"EmpID\t Hours\t Pay\n");
for(int j = 0; j < numEmp; j++)
{
/*If statement for an employee that works over 40 hours */
if(wkHrs[j][i] > 40)
{
fprintf(ofp, "\t %d\t %lf\t %lf", j, wkHrs[j][i], (Emp[j][1]*40)+(wkHrs[j][i]-40)*1.5*Emp[j][1]);
}
else
{
fprintf(ofp, "\t %d\t %lf\t %lf", j, wkHrs[j][i], Emp[j][1]*wkHrs[j][i]);
}
}
}
fprintf(ofp, "Total\n");
fprintf(ofp, "EmpID\t Hours\t Pay\n");
for(int j = 0; j < numEmp; j++)
{
fprintf(ofp, "\t %d\t %lf\t %lf", j, Emp[j][0], Emp[j][1]*Emp[j][0]);
}
fclose(ofp);
}
This is what the output should look like.
Number of employees: 2
Number of weeks: 3
Wk 1
EmpID Hours Pay
0 9.50 52.25
1 3.00 30.00
Wk 2
EmpID Hours Pay
0 5.50 30.25
1 45.00 450.00
Wk 3
EmpID Hours Pay
0 7.00 38.5.00
1 4.00 40.00
Total
EmpID Hours Pay
0 22.00 121.00
1 52.00 520.00
This is what I get in my payroll.o file
Number of weeks: %d
Wk%d
EmpID Hours Pay
%d %lf %lfTotal
qÄzRxê$#¯ˇˇˇˇˇˇAÜC
$D˚ˇˇˇˇˇˇqAÜC
$lp˚ˇˇˇˇˇˇAÜC
-c-
In your printLog the last parameter should be of type double, not int.
Why am I unable to scan the elements from a file with the following prog? I am able to scan for the elements using a while loop. However, i wanted to put the elements in a 2-D Array, that is the reason I tried to use the for loop instead. Unfortunately, I am just not able to do it. Is there any particular reason for this, or am I doing something wrong.
Screen Shot of the error given below.
#include <stdio.h>
#define ROW 3
#define COLUMN 12
#define SIZE 40
int main ()
{
int i ,j;
float sale[ROW][COLUMN];
FILE *fp;
fp = fopen("store.txt", "r");
if(fp == NULL)
{
printf("Error Opening File\n");
return 0;
}
for(i=0; i<ROW; i++)
{
for(j=0; j<COLUMN; j++)
{
fscanf(fp, "%.2f", &sale[i][j]);
printf("%.2f ", sale[i][j]);
}
printf("\n\n");
}
fclose(fp);
return 0;
}
Elements are
A 20000 15000 14000 14900 17800 12000 11500 11000 15700 18500 20400 31000
B 31900 17000 16700 17800 18800 22000 10500 11000 15890 17640 21750 32540
c 29000 17500 16600 14678 17970 12125 11576 12198 16700 19500 21400 31000
You must not use %Ld, it is invalid. You should use either %ld for a long int or %Lf for a long double.
See here the complete table showing valid combinations: http://www.cplusplus.com/reference/cstdio/scanf/
Also, remember to check the return value of your functions, specially here fscanf can fail without you noticing.
Also consider initializing your sale array. The output you show is due to uninitialized memory.
I think the problem is this statement.
fscanf(fp, "%.2f", &sale[i][j]);
In fsanf format %.2f is invalid.In printf is OK.
In addition, you need to read the first char element,otherwise,can not read successful.
You can do it like this.
char buf[ROW];//for A B C
for(i=0,fscanf(fp,"%c",&buf[i]); i<ROW; i++)
{
for(j=0; j<COLUMN; j++)
{
fscanf(fp, "%f", &sale[i][j]);
printf("%.2f", sale[i][j]);
}
printf("\n\n");
}
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);
}