Read a file but avoid duplicate data - c

My code below reads a file in c which contains a list of students names(name and last name) and their scores, it prints the file, finds the average score, the highest score and prints the students' names who obtained the highest score. My problem is that some student's names and grades are repeated in the file. So I want to know how could I read the same file but only print a list in which there are not duplicates names and scores. So next I can update the rest of information that I am looking for(ie. average).
#define MAX 30 // Maximum number of students
#define MINRANGE 0 // range of scores
#define MAXRANGE 100
int computeMax(double stSco[], int numSt); //Gets the average and highest score
void outputBest(double number[], char nameHigh[][16], int highPl, int totalSt);
//Students with the highest score
int main()
{
double score[MAX];
char name[MAX][16];
char fileName[80];
int k, count=0, hgCt;
stream dataFile;
banner();
printf("Type the name of file you want to read\n");
scanf("%79[^\n]", fileName);
puts(" Grade Student\n");//Header
dataFile = fopen(fileName, "r");
if(dataFile == NULL){
fatal( "Cannot open %s for reading", fileName);
}
for(k=0; k < MAX; k++){
fscanf(dataFile, "%lg %16[^\n]", &score[k], name[k]);
if(feof(dataFile)) break;
if(score[k] >= MINRANGE && score[k] <= MAXRANGE){ //Score validation
printf("%6.1f %s\n", score[k], name[k]);
count++; //It counts how many students there are actually
}
else{
fatal( "There are illegal grades in file %s", fileName);
}
}
fclose(dataFile);
if(count == 0){ //Checks if file is empty
fatal( "The file %s is empty", fileName);
}
else {
hgCt = computeMax(score, count); //Stores the returned highest score
outputBest(score, name, hgCt, count);
bye();
}
return 0;
}

Related

How to find matching values in two arrays?

I need to get the user to input 6 numbers and I store those in an array called winningNum[]. Then I have to read in a file that has a bunch of users firstName lastName and the numbers they have guessed. I need to compare these two arrays and only print out the first and last name of the users from the file that got a minimum of three numbers matched.
This is the struct of for the input file users
typedef struct
{
char firstName [20];
char lastName [20];
int numbers[6];
}KBLottoPlayer;
Getting the winning numbers from the user
int getNum()
{
int winningNum[6];
int i;
printf("Please enter the six nunbers between 1-53:\n");
scanf("%d %d %d %d %d %d", &winningNum[0], &winningNum[1],
&winningNum[2] ,&winningNum[3], &winningNum[4], &winningNum[5] );
}
This is where I am reading in the file and putting it into the struct array
KBLottoPlayer* readArray()
{
int i,size;
FILE *in = fopen("KnightsBall.in","r");
fscanf(in,"%d",&size);
KBLottoPlayer* temp;
temp =(KBLottoPlayer*)malloc(sizeof(KBLottoPlayer)*size);
if((in = fopen("KnightsBall.in", "r")) != NULL )
{
char buffer[100];
fgets(buffer, 5, in);
for(i=0;i<size;i++)
{
fscanf(in," %s %s ", temp[i].firstName, temp[i].lastName);
fscanf(in,"%d %d %d %d %d %d ", &temp[i].numbers[0],
&temp[i].numbers[1], &temp[i].numbers[2], &temp[i].numbers[3],
&temp[i].numbers[4], &temp[i].numbers[5]);
}
}
else
{
printf("File is Not Exist.\n");
}
return temp;
}
I essentially need to only store the first and last name of the users that got 3 4 5 6 of the winning numbers correct.
I will admit that you only need hints to go past a problem.
Unrelated, but you never test your input functions. Beware a single incorrect line will give undefined results and you will not even know where the problem is. Remember: never trust what comes from the outside.
Back to your problem. A simple way is to use 2 nested loops, one on the winning numbers and one on the guessed ones just counting the matches: if the total number of matches is at least 3, you keep the record, else you reject it. You can even do that when reading the file (here in pseudo-code):
int recnum = 0; // next record to store
for (int i=0; i<size; i++) { // loop over the input file
read the line into temp[recnum]
int count = 0; // number of correct guesses
for (int j=0; j<6; j++) { // loop over the winning numbers
for (int k=0; k<6; k++) { // loop over the guessed numbers
if winning[j] == guessed[k] {
count++;
}
}
}
if (count >= 3) recnum++; // only keep if at least 3 correct guesses
}

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

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.

Storing Data Char Array C

[I write the program in C language]
I would like to read a txt file containing StudentName, Score, and Remarks
The pattern of the txt file looks like this:
1,Adam Lambert,60,C
2,Josh Roberts,100,A
3,Catherine Zetta,80,B
I would like to store each data, respectively into an array
So I would have 3 arrays (to store StudentName, Scores, and Grades)
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <math.h>
char* studName[99];
char* grade[99];
char* grades[100][10];
char buff[1024];
int scores[100];
int score;
int index;
int size;
int index = 0;
int sum = 0;
double average = 0;
int main()
{
FILE *file;
file = fopen("notepad.txt", "r");
if(file == NULL){
printf("Data does not Exist");
}
else {
while(((fgets(buff,1024,file))!=NULL))
{
size = strlen(buff);
buff[size] = 0;
sscanf(buff, "%d, %[^,],%d, %[^,]", &index, studName,&score, grade);
printf("Student Name: %s\n", studName);
printf("Score: %d\n", score);
printf("Remark: %s\n", grade);
scores[index-1] = score;
grades[index-1][10] = grade;
sum+=score;
index++;
}
}
fclose(file);
average = sum/index;
printf("\nThe total score of student is: %d\n", sum);
printf("\nThe sum of student is: %d\n", index);
printf("\nThe average of students' score is: %2f\n", average);
for(int i = 0; i<3; i++){
printf("Score: %d\n", scores[i]);
printf("\nThe Remark is: %s\n", grades[i][10]);
}
getch();
return 0;
}
The code above had successfully stored the scores in int array. I had not really good in C, so I do not know how to store the char array for StudentName and Grades.
The abovde code gives the result of Grades stored is only the last grade on the txt file (in this case is 'B').
Would you please tell me what do I have to fix in order to achieve my goal?
My goal basically will be pretty much like this:
StudentName array contains {"Adam Lambert", "Josh Roberts", "Catherine Zetta"}
Scores array contains {60,100,80}
Grades array contains {"C", "A", "B"}
Thank you very much.
Change studName and grade from "char *" to "char". You want a buffer, not an array of pointers.
At the top add:
char * StudentName[100];
When setting "scores" and "grades" add:
StudentName[index-1] = strdup(studName);
Also change the "10" in the following line, the array only dimensions 0-9.
grades[index-1][10] = grade;
Try this:
float len=sizeof(string);
Just gives you the static size of the array string which is an array of 20 pointers and each pointer is 4 bytes, 20 * 4 bytes = 80 that's why it's always 80.
while (fgets(string[i], BUFSIZE, fp)) {
i++;
len+=strlen(string[i]);
string[i] = (char *)malloc(BUFSIZE);
}
If your recore size is fixed then u can use this:
Where fr is a file pointer
fscanf(fr, "Index: %d StuName: %s Score: %d Grade: %s ", &index, sname, &score, grade);

Reading a file in C and store data in arrays

My code below reads a file in C.It displays the file, the average score, maximum score,and the names of all the students who earned the maximum score. The exam scores(0-100 format to 1 decimal place and use a field width of columns) are stored in an array and the names(name and last name limited to 15 characters) are stored in a 2-dimensional array of characters that is parallel to the scores array. My problems are:
1) The code doesn't read(print) the file properly (I think is related to fscanf and the arrays).
2) My two functions don't print the results.
Any suggestion is appreciated, thanks.
#include "tools.h"
#define MAX 30 // Maximum number of students
int computeMax(double stSco[], int numSt); // Gets the average and highest
// score
void outputBest(double num[], char nameHg[][15], int hgPl, int totStu);
int main()
{
double score[MAX];
char name[MAX][15];
char fileName[80];
int k, count = 0, hgCt;
stream dataFile;
banner();
printf("Type the name of file you want to read\n");
scanf("%79[^/n]", fileName);
dataFile = fopen(fileName, "r");
if (dataFile == NULL)
{
fatal("Cannot open %s for input", fileName);
}
while (!feof(dataFile))
{
fscanf(dataFile, "(%lg,%s)", &score[k], &name[k]);
printf("%6.1f %s\n", score[k], name[k]);
count++; // It counts how many students there are
}
hgCt = computeMax(score, count); // Stores the value sent by the
// function
outputBest(score, name, hgCt, count);
fclose(dataFile);
bye();
return 0;
}
int computeMax(double stSco[], int numSt)
{
int k, maxScore = 0, sum = 0;
double maximum = 0, average = 0;
for (k = 0; k < numSt; k++)
{
sum += stSco[k]; // It sums all scores
if (stSco[k] > maximum)
{
maximum = stSco[k];
maxScore = k; // Stores the index of the maximum score
}
}
average = sum / numSt;
printf("The average score is %d\n", average);
printf("The maximum score is %d\n", maximum);
return maxScore;
}
void outputBest(double num[], char nameHg[][15], int hgPl, int totStu)
{
int k;
for (k = 0; k < totStu; k++)
{
if (num[k] = hgPl)
{ // It finds who has the highest score
printf("%s got the highest score\n", nameHg[k]);
}
}
}
First: scanf("%79[^/n]",fileName); should be scanf("%79[^\n]",fileName);, better to use fgets().
Second typo mistake: misspelled == by = in if() condition
if(num[k]=hgPl){ //It finds who has the highest score
// ^ = wrong
should be:
if(num[k] == hgPl){ //It finds who has the highest score
Edit:
Error in while loop..
fscanf(dataFile, "(%lg,%s)", &score[k], &name[k]);
// ^ ^ ^ remove ^
should be:
fscanf(dataFile, "%lg%14s", &score[k], name[k]);
and increment k in while loop. after printf("%6.1f %s\n", score[k], name[k]);.

Resources