adding using file integers input - c

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);

Related

Why am I receiving "Segmentation fault: 11"

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

Multiple file program

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);
}

C asking for user txt file, saving in array, and outputting in txt

So I have a function built already that calculated 25 random temperatures and outputted them and had a max, min, and average feature. I'm now trying to incorporate input files and output files via txt.
I tried to do some research and plug in what I could (even if I barely understood it), can someone lend some light on my code?
int get_value(void);
void calc_results(void);
void read_temps(void);
int sum = 0;
int min = 0;
int max = 0;
int temp[25];
int i = 0; //For array loop
int j = 0; //For printf loop
float avg = 0;
void read_temps() {
char fname[128];
printf("Enter .txt file name \n");
scanf("%123s", fname);
strcat(fname, ".txt");
FILE *inputf;
inputf=fopen(fname, "w");
for (i = 0; i < 25; i++){
temp[i] = fname;
sum += temp[i];
}
}
int main () {
calc_results();
return 0;
};
void calc_results(void) {
FILE * fp;
fp = fopen("Output_temps.txt", "w+");
avg = ((sum)/(25));
max = temp[0];
for(i=1;i<25;i++){
if(max<temp[i])
max=temp[i];
};
min =temp[0];
for(i=1;i<25;i++){
if(min>temp[i])
min=temp[i];
};
fprintf("Temperature Conditions on October 9, 2015 : \n");
fprintf("Time of day Temperature in degrees F \n");
for(j=0;j<25;j++){
fprintf(" %d %d\n",j,temp[j]);
}
fprintf("Maximum Temperature for the day: %d Degrees F\n", max);
fprintf("Minimum Temperature for the day: %d Degrees F\n", min);
fprintf("Average Temperature for the day: %.1f Degrees F\n", avg);
fclose(fp);
};
There were a few errors in your code, the most critical one being it doesn't compile. If you're having issues you'll want to follow the instructions for how to make a ssce. You will get a much better response this way. Then explain clearly the specific issue you are having and what it is that is happening or not happening as opposed to what you expect.
With your code you seem to be assigning to your temp array the fname variable instead of reading in the int data from the user file.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// assuming you want a maximum of temperatures of 25
#define TEMP_NUMBER 25
// use a struct to maintain and the temparatur data in one place
// without resorting to using global variables or having functions
// that require numerous parameters.
struct temp_data {
char fname[128];
int max;
int min;
int sum;
int temps[TEMP_NUMBER];
float avg;
};
struct temp_data *temps_init(void)
{
// creates a pointer to struct temp_data to hold
// your various temparture related fields
struct temp_data *td = malloc(sizeof *td);
td->sum = 0;
td->avg = 0.0;
return td;
}
void read_temps(struct temp_data *td)
{
// in your sample code you have this set to "w", needs to be "r"
FILE *inputf = fopen(td->fname, "r");
// handle error
if (!inputf) {
perror("fopen");
exit(0);
}
for (int i = 0; i < TEMP_NUMBER; i++) {
// you were setting fname to the temparature array
// instead you need to scan the temp file
fscanf(inputf, "%d", &(td->temps[i]));
td->sum += td->temps[i];
}
}
void print_results(struct temp_data *td)
{
// a print function to separate logic
FILE *fp = fopen("Output_temps.txt", "w+");
if (!fp) {
perror("fopen");
exit(0);
}
fprintf(fp, "Temperature Conditions on October 9, 2015 : \n");
fprintf(fp, "Time of day Temperature in degrees F \n");
for(int i=0; i < TEMP_NUMBER; i++)
fprintf(fp, " %d %d\n", i, td->temps[i]);
fprintf(fp, "Maximum Temperature for the day: %d Degrees F\n", td->max);
fprintf(fp, "Minimum Temperature for the day: %d Degrees F\n", td->min);
fprintf(fp, "Average Temperature for the day: %.1f Degrees F\n", td->avg);
fclose(fp);
}
void calc_results(struct temp_data *td)
{
// do only calculations
td->avg = td->sum / TEMP_NUMBER;
td->min = td->temps[0];
td->max = td->temps[0];
for (int i=1; i < TEMP_NUMBER; i++) {
td->min = td->temps[i] < td->min ? td->temps[i] : td->min;
td->max = td->temps[i] > td->max ? td->temps[i] : td->max;
}
}
int main(int argc, char *argv[])
{
// Moved user input into the main() from read_temps()
// now read_temps() only needs to read and record the temp data
struct temp_data *td = temps_init();
printf("Enter .txt file name \n");
scanf("%123s", td->fname);
strcat(td->fname, ".txt");
read_temps(td);
calc_results(td);
print_results(td);
free(td);
return 0;
};
Using a file called sample.txt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

how to read specific value from file in c

if i have file contain students scores
for example this file
{
students scores :
100
90
83
70
}
how i can read just the values of scores with out reading "students scores :"???
mu code is already ok
but the problem in reading values
this is my code
#include <stdio.h>
int main (void)
{
FILE *infile;
double score, sum=0, average;
int count=0, input_status;
infile = fopen("scores.txt", "r");
input_status = fscanf(infile, "%lf", &score);
while (input_status != EOF)
{
printf("%.2f\n ", score);
sum += score;
count++;
input_status = fscanf(infile, "%lf", &score);
}
average = sum / count;
printf("\nSum of the scores is %f\n", sum);
printf("Average score is %.2f\n", average);
fclose(infile);
getch();
}
Problems I see:
input_status = fscanf(infile, "%lf", &score);
while (input_status != EOF)
is not right. The returned value of fscanf will be 0 if the read was not successful and 1 if it was successful.
More importantly, you need to add code that skips everything upto the point where you expect to see the numbers.
char line[100];
while ( fgets(line, 100, infile) != NULL )
{
// If the line containing "students scores :"
// is found, break from the while loop.
if (strstr(line, "students scores :") != NULL )
{
break;
}
}
Then, change start of the lines that read the data into:
input_status = fscanf(infile, "%lf", &score);
while (input_status == 1 )
Here's a fairly easy way to parse the file.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main (void)
{
FILE *infile;
char lineBuf[255+1];
double score, sum=0, average;
int count=0;
int fieldsParsed;
infile = fopen("scores.txt", "r");
/** Read a line from the file. **/
while(fgets(lineBuf, sizeof(lineBuf), infile))
{
/** Is the first character of the line a digit? **/
if(!isdigit(*lineBuf))
continue; /* It is not a digit. Go get the next line. */
/** Convert the number string (in lineBuf) to an integer (score). **/
score=atof(lineBuf);
printf("fields[%d] %.2f\n ", fieldsParsed, score);
sum += score;
count++;
}
average = sum / count;
printf("\nSum of the scores is %f\n", sum);
printf("Average score is %.2f\n", average);
fclose(infile);
// getch(); Non-portable
return(0);
}
Use fseek() to skip past the leading bytes to the numbers.

Read from file and do calculations. C program

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);
}

Resources