How can I read data's from .txt file in C? - c

I want to read the information that I saved in txt file in the program I created. but when I want to do the reading process only the first line of student information by reading, for example, class 10 people are writing the same student information 10 times within the program. I'm doing the read operation in the for loop.
struct student{
char Name[30];
char Surname[30];
int StudentNumber;
int MathematicScore;
int EnglishScore;
int HistoryScore;
int BiologyScore;
int LiteratureScore;
int PhysicsScore;
int classNum;
int total;
float average;
};
/* Printing process */
FILE *fout;
fout = fopen("Mathematic Class.txt","w");
printf("Please enter student number of class : ");
scanf("%d", &x.classNum);
fprintf(fout, "Class Number : %d\n",x.classNum);
for(i=0; i<x.classNum; i++){
printf("Please Enter %d.Student Name : ",i+1);
scanf("%s",&x.Name);
printf("Please Enter %d.Student Surname : ",i+1);
scanf("%s",&x.Surname);
printf("Please Enter %d.Student Number : ",i+1);
scanf("%d",&x.StudentNumber);
printf("Please Enter %d.Student Score : ",i+1);
scanf("%d",&x.MathematicScore);
x.total = x.total + x.MathematicScore;
fprintf(fout, "\nStudent Name : %s %s Student Number : %d Student Score : %d\n", x.Name, x.Surname, x.StudentNumber, x.MathematicScore);
}
x.average = x.total / x.classNum;
fprintf(fout, "\n\nClass Average is : %f", x.average);
fclose(fout);
/* Reading process */
FILE *fin;
fin = fopen("Mathematic Class.txt","r");
fscanf(fin, "Class Number : %d\n\n%s %s %d %d\n",&x.classNum, &x.Name, &x.Surname, &x.StudentNumber, &x.MathematicScore, &x.average);
fclose(fin);
printf("Class Number : %d\n", x.classNum);
for(i=0; i<x.classNum; i++){
printf("Student Name : %s %s Student Number : %d Student Score : %d\n", x.Name, x.Surname, x.StudentNumber, x.MathematicScore);
}
printf("\n\nClass Average is : %f", x.average);

Here are the problems that I see upon first look:
You only call fscanf() one time in the reading process. If you want to read in data for multiple students, like it appears you're doing in the writing process, you need to call it once for each student to read that student's line from the file.
In your reading/printing process, you are printing the same data x.classNum times.

Related

C Structure Program showing garbage in numeric values

This code is about structures and includes basic input from the user but somehow that is not working properly with numeric values such as age, salary etc. I have tried fflush() but got no luck from using that and I can't find any other solution on the internet, everything except the garbage value works like a charm in this code
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct employee
{
unsigned int id;
char name[30];
int age;
char address[50];
char department[30];
unsigned int salary;
};
void main()
{
int i,num;
struct employee emp[50];
printf("\nEnter number of employees whose data you want to enter : ");
scanf("%d", &num);
for(i=0;i<num;i++)
{
printf("\n||| EMPLOYEE NUMBER %d |||\n",i+1);
printf("\nEnter your employee ID (5 Digits) : ");
fflush(stdin);
scanf("%u", &emp[i].id);
printf("\nEnter your name : ");
fflush(stdin);
gets(emp[i].name);
printf("\nEnter your age : ");
fflush(stdin);
scanf("%d", &emp[i].age);
printf("\nEnter your address : ");
fflush(stdin);
gets(emp[i].address);
printf("\nEnter your department : ");
fflush(stdin);
gets(emp[i].department);
printf("\nEnter your salary : ");
fflush(stdin);
scanf("%u", &emp[i].salary);
}
for(i=0;i<num;i++)
{
printf("\n||| EMPLOYEE %d DETAILS ARE |||", i+1);
printf("\nID : %u", &emp[i].id);
printf("\nNAME : %s", emp[i].name);
printf("\nAGE : %d", &emp[i].age);
printf("\nADDRESS : %s", emp[i].address);
printf("\nDEPARTMENT : %s", emp[i].department);
printf("\nSALARY : %u", &emp[i].salary);
}
getch();
}
USER INPUT
||| EMPLOYEE NUMBER 1 |||
Enter your employee ID (5 Digits) : 12345
Enter your name : The Crow
Enter your age : 24
Enter your address : 25/45 New York
Enter your department : HR
Enter your salary : 23000
OUTPUT
||| EMPLOYEE 1 DETAILS ARE |||
ID : 6612448
NAME : The Crow
AGE : 6612484
ADDRESS : 25/45 New York
DEPARTMENT : HR
SALARY : 6612568
Input:
Output:
You are printing the address of id, age, and salary. Delete the & in front of them in your printf statements to print their values.
printf("\n||| EMPLOYEE %d DETAILS ARE |||", i+1);
printf("\nID : %u", emp[i].id);
printf("\nNAME : %s", emp[i].name);
printf("\nAGE : %d", emp[i].age);
printf("\nADDRESS : %s", emp[i].address);
printf("\nDEPARTMENT : %s", emp[i].department);
printf("\nSALARY : %u", emp[i].salary);
On another note, main has return type int so you should define it like this
int main(int argc, char** argv) {
// your code goes here
return 0;
}
As #pm100 mentioned in the comments:
Never use gets. Use fgets.
Read the outputs of the compiler carefully. They are often very informative.

MY code is only displaying the input which i entered at the very end. I have attached my full code. PLEASE help me find where i am doing it wrong

QUESTION:
WAP to enter id, name, age and basic salary of n number of employees. Calculate the gross salary of all the employees and display it along with all other details in a tabular form, using pointer to structure.
--->
#include <stdio.h>
#include <conio.h>
struct employee {
char name[100];
int id, age;
int salary;
};
int main(){
struct employee emp, *ptr;
int i,n;
printf("Enter the no of employees\n");
scanf("%d",&n);
printf("****************INPUT EMPLOYEE DETAILS******************\n");
for(i=0;i<n;i++)
{
printf("\nEnter employee id of employee %d : ",i+1);
scanf("%d", &emp.id);
printf("Enter name of employee %d : ", i+1);
scanf("%s", &emp.name);
printf("Enter age of employee %d : ", i+1);
scanf("%d", &emp.age);
printf("Enter salary of employee %d : ", i+1);
scanf("%d", &emp.salary);
}
printf("\n");
printf(" DISPLAYING EMPLOYEE DETAILS \n");
printf("*********************************************************************\n");
ptr = &emp;
printf("\nEMP_ID\t\tEMP_NAME\tEMP_AGE\t\tGROSS_SAL\n");
for(i=0;i<n;i++){
printf("%d\t\t%s\t\t%d\t\t%d\n",ptr->id, ptr->name, ptr->age, ptr->salary);
}
return 0;
}
First of all you need to save each of your employees in variable so you can refer them later. Second because your variable is structure and you want loop through it your best choice is to use array.
I changed your code and highlighted them it worked for me i hope it will help you.
#include <stdio.h>
#include <conio.h>
struct employee {
char name[100];
int id, age;
int salary;
};
int main(){
struct employee *ptr; //One change is here
int i,n;
printf("Enter the no of employees\n");
scanf("%d",&n);
struct employee emp[n];
printf("****************INPUT EMPLOYEE DETAILS******************\n");
for(i=0;i<n;i++)
{
printf("\nEnter employee id of employee %d : ",i+1);
scanf("%d", &emp[i].id);
printf("Enter name of employee %d : ", i+1);
scanf("%s", emp[i].name); // Another change is here "%s" doesn't need '&'
printf("Enter age of employee %d : ", i+1);
scanf("%d", &emp[i].age);
printf("Enter salary of employee %d : ", i+1);
scanf("%d", &emp[i].salary);
}
printf("\n");
printf(" DISPLAYING EMPLOYEE DETAILS \n");
printf("*********************************************************************\n");
printf("\nEMP_ID\t\tEMP_NAME\tEMP_AGE\t\tGROSS_SAL\n");
for(i=0;i<n;i++){
ptr = &emp[i]; // This yet another change i grab "ptr" down here and assign it to "i" in each loop
printf("%d\t\t%s\t\t%d\t\t%d\n",ptr->id, ptr->name, ptr->age, ptr->salary);
}
return 0;
}

can anyone tell me where is the mistakes? [duplicate]

This question already has an answer here:
C Access violation writing location scanf_s
(1 answer)
Closed 1 year ago.
While the program is running , in the middle of it (after typing the Vaccine name ) it stops and gives me {Exception Thrown} can anyone help me fix this issue? I have also included a photo of the error it gives me
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int choose, dosage, quantity;
char code[10];
char name[32];
char produce[64];
float population;
{
printf("COVID-19 Vaccination System \n");
printf("1:- Inventory Creation \n");
printf("2:- Update Vaccine Quantities \n");
printf("3:- Search Vaccine \n");
printf("4:- Produce a list of all Vaccines and their distributed Quantities \n");
printf("5:- EXIT \n\n");
printf("==>");
scanf_s("\n%d", &choose);
if (choose == 1)
{
char ch;
FILE* cv;
errno_t err;
err = fopen_s(&cv, "vaccine.txt", "w");
for (int i = 0; i < 5; i++)
{
printf("Please Enter Vaccine Full information %d \n", i + 1);
printf(" Name of Vaccine : ");
scanf_s("\n%s", &name);
printf("Please Enter Vaccine Code %c \n", i + 1);
printf(" Vaccine Code : ");
scanf_s("\n%s", &code);
printf("Please Enter Vaccine Producing Country %c \n", i + 1);
printf("Producing Country : ");
scanf_s("\n%s", &produce);
printf("Please Enter Dosage Required %d \n", i + 1);
printf("Dosage Required (MAX=2 - MIN=1) : ");
scanf_s("\n%d", &dosage);
printf("Please Enter Population Covered %d \n", i + 1);
printf("Population Covered (%) : ");
scanf_s("\n%f", &population);
printf("Please Enter Vaccine Quantity %d \n", i + 1);
scanf_s("\n%d", &quantity);
fprintf("%s %s %s %d %f %d", name, code, produce, dosage, population, quantity);
}
}
}
return 0;
}
The line
fprintf("%s %s %s %d %f %d", name, code, produce, dosage, population, quantity);
is wrong. You have to pass a file pointer as the first argument of fprintf(). It should be:
fprintf(cv, "%s %s %s %d %f %d", name, code, produce, dosage, population, quantity);
Also
You should check if fopen_s succeeded before proceeding to next operation and stop operation if it failed.
You should remove & before the array names (code, name, produce) used in scanf_s. Array in expressions (excluding some exceptions) are automatically converted to pointers to the first element, so no explicit & is not needed here. Also it will make the type wrong scanf() expects char* for %s, but things like &code are an pointers to arrays (like char(*)[10]).

Printing structures using loop

How to print structure contents using for-loop? If pointers, how to assign pointer to structure? I have attached code that I made that makes a structure using data that user inputs, and prints them out in an orderly fashion. My problem is that you have to write a lot of printf() and gets_s() statements to receive and print input. I feel like it would be easier to do this using a for-loop. I tried to make a for-loop as you can see in the code using pointers, but it doesn't compile, and I'm pretty sure that it is the wrong way to assign pointers to structures.
TL;DR: How to print structure contents using for-loop? If pointers, how to assign pointer to structure?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
#define maxName 50
#define maxNation 50
#define maxAge 100
struct astronaut
{
char firstName[maxName];
char lastName[maxName];
char nation[maxNation];
int age = 0;
char missionName[maxAge];
int missionYear[50];
};
int main()
{
int i = 0;
struct astronaut candidate1;
struct astronaut candidate2;
struct astronaut candidate3;
struct astronaut mission1;
struct astronaut mission2;
struct astronaut mission3;
printf("Please enter the first name of the candidate: ");
gets_s(candidate1.firstName);
printf("Please enter the last name of the candidate: ");
gets_s(candidate1.lastName);
printf("Please enter the nationality of the candidate: ");
gets_s(candidate1.nation);
printf("Please enter the age of the candidate: ");
scanf("%d", &candidate1.age);
printf("Please enter the first name of the candidate: ");
gets_s(candidate2.firstName);
printf("Please enter the last name of the candidate: ");
gets_s(candidate2.lastName);
printf("Please enter the nationality of the candidate: ");
gets_s(candidate2.nation);
printf("Please enter the age of the candidate: ");
scanf("%d", &candidate2.age);
printf("Please enter the first name of the candidate: ");
gets_s(candidate3.firstName);
printf("Please enter the last name of the candidate: ");
gets_s(candidate3.lastName);
printf("Please enter the nationality of the candidate: ");
gets_s(candidate3.nation);
printf("Please enter the age of the candidate: ");
scanf("%d", &candidate3.age);
printf("Enter a Mission Name: ");
gets_s(mission1.missionName);
printf("Enter the year the mission was conducted: ");
scanf("%d", &mission1.missionYear);
printf("Enter a Mission Name: ");
gets_s(mission2.missionName);
printf("Enter the year the mission was conducted: ");
scanf("%d", &mission2.missionYear);
printf("Enter a Mission Name: ");
gets_s(mission3.missionName);
printf("Enter the year the mission was conducted: ");
scanf("%d", &mission3.missionYear);
struct astronaut *ptr;
struct candidate *ptr;
// printf("\n\tAstronaut Candidate Database\n");
// printf("Name: %s %s \t Age: %d \t Nationality: %s\n", candidate1.firstName, candidate1.lastName, candidate1.age, candidate1.nation);
// printf("Name: %s %s \t Age: %d \t Nationality: %s\n", candidate2.firstName, candidate2.lastName, candidate2.age, candidate2.nation);
// printf("Name: %s %s \t Age: %d \t Nationality: %s\n", candidate3.firstName, candidate3.lastName, candidate3.age, candidate3.nation);
// printf("\n\tAstronaut Mission Database\n");
// printf("Mission Name: %s \t Year: %d\n", mission1.missionName, mission1.missionYear);
// printf("Mission Name: %s \t Year: %d\n", mission2.missionName, mission2.missionYear);
// printf("Mission Name: %s \t Year: %d\n", mission3.missionName, mission3.missionYear);
for (int index = 0; index < 5; index++)
{
printf("Name: %s %s \t Age: %d \t Nationality: %s\n", *ptr.firstName, *ptr.lastName, *ptr.age, *ptr.nation);
ptr++;
}
_getch();
return 0;
}
I think you need 2 structs. An astronaut and a mission aren't the same thing. As it is now, you have several unused fields depending on whether you're entering data for an astronaut or a mission. You could do something like this:
#include <stdio.h>
#define maxName 50
#define maxNation 50
#define maxAge 100
struct astronaut
{
char firstName[maxName];
char lastName[maxName];
char nation[maxNation];
int age;
};
struct mission
{
char missionName[maxAge];
int missionYear; // why do you have an array of 50 ints for the missionYear?
};
void enter_candidate_data(struct candidate* cand)
{
// not famliar with gets_s .. I would use fgets here, you can read the manpage on that if you desire
printf("Please enter the first name of the candidate: ");
gets_s(cand->firstName);
printf("Please enter the last name of the candidate: ");
gets_s(cand->lastName);
printf("Please enter the nationality of the candidate: ");
gets_s(cand->nation);
printf("Please enter the age of the candidate: ");
scanf("%d", &(cand->age));
}
void enter_mission_data(struct mission* mis)
{
printf("Enter a Mission Name: ");
gets_s(mis->missionName);
printf("Enter the year the mission was conducted: ");
scanf("%d", &(mis->missionYear));
}
int main()
{
int i;
struct astronaut candidates[3];
struct mission missions[3];
for (i=0; i<3; i++)
{
enter_candidate_data(&(candidates[i]));
// you can put this in a separate loop if you want to enter all
// candidate data first
enter_mission_data(&(missions[i]));
}
// you could also write functions to print the data instead, depends on
// how you want it all presented
for (int i=0; i<3; i++)
{
printf("Name: %s %s \t Age: %d \t Nationality: %s\n",
candidates[i].firstName, candidates[i].lastName, candidates[i].nation);
printf("Mission Name: %s, year %d\n", missions[i].missionName,
missions[i].missionYear);
}
return 0;
}
You may want a number of missions (or even just one) associated with a particular astronaut. If so, I would define the data structures like this
#define MAX_ASTRONAUT_MISSIONS 20
struct mission
{
char missionName[maxAge];
int missionYear;
};
struct astronaut
{
char firstName[maxName];
char lastName[maxName];
char nation[maxNation];
int age;
struct mission missions[MAX_ASTRONAUT_MISSIONS];
};
This will allow you to associate MAX_ASTRONAUT_MISSION missions with each astronaut. Or, more realistically, a single mission could be associated with several astronauts. In that case, you may want data structures more like this
struct mission
{
char missionName[maxAge];
int missionYear;
};
struct astronaut
{
char firstName[maxName];
char lastName[maxName];
char nation[maxNation];
int age;
// using a pointer to missions will allow you to create one mission, and
// all the astronauts on that mission could get a pointer to it,
// designating they were all on that singular mission.
struct mission* missions[MAX_ASTRONAUT_MISSIONS];
};

Unable to enter Name with Spaces in C program?

This program asks for employee name, age and Salary. There is one slight problem and i don't know what this wrong. When i enter name without space or just the first name, then program works correctly but as soon as i enter full name with space. The program just skips some values without asking and jumps to other values. I know their is something wrong with scant of "worker[i].name" and i have tried %c too but with no success.
struct employee {
int pAge;
float salary;
char name[30];
};
int main(void) {
struct employee worker[2];
for (int i = 0; i < 2; i++) {
printf("Enter Name of %d employee: ", (i+1));
scanf(" %s", worker[i].name);
printf("Enter Age of %d employee: ", (i+1));
scanf("%d", &worker[i].pAge);
printf("Enter Salary of %d employee: ", (i+1));
scanf("%f", &worker[i].salary);
}
printf("\n");
printf("List of All workers\n\n");
printf( "Age\tSalary\t\tName\n");
for (int i = 0; i < 2; i++) {
printf("%d\t%.2f\t\t%s\n", worker[i].pAge, worker[i].salary, worker[i].name);
}
}
Its very simple just use this instead:
scanf(" %[^\n]s", worker[i].name);

Resources