Tuesday, June 3, 2025
C Coding
#include
#include
#include
#define MAX_NAME_LENGTH 100
#define MAX_STUDENTS 50
// Define a structure to store student information
typedef struct {
int id;
char name[MAX_NAME_LENGTH];
float grade;
} Student;
// Function to input student data
void inputStudentData(Student* student, int index) {
printf("Enter data for student %d\n", index + 1);
printf("ID: ");
scanf("%d", &student->id);
printf("Name: ");
getchar(); // Clear newline character from buffer
fgets(student->name, MAX_NAME_LENGTH, stdin);
student->name[strcspn(student->name, "\n")] = 0; // Remove newline
printf("Grade: ");
scanf("%f", &student->grade);
}
// Function to write student data to a file
void writeToFile(const char* filename, Student* students, int count) {
FILE* file = fopen(filename, "w");
if (file == NULL) {
printf("Error opening file for writing.\n");
return;
}
for (int i = 0; i < count; ++i) {
fprintf(file, "%d,%s,%.2f\n", students[i].id, students[i].name, students[i].grade);
}
fclose(file);
printf("Data written to file successfully.\n");
}
// Function to read and display student data from a file
void readFromFile(const char* filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("Error opening file for reading.\n");
return;
}
char line[150];
printf("\n--- Student Data from File ---\n");
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
fclose(file);
}
int main() {
Student students[MAX_STUDENTS];
int studentCount;
printf("How many students do you want to enter (max %d)? ", MAX_STUDENTS);
scanf("%d", &studentCount);
if (studentCount < 1 || studentCount > MAX_STUDENTS) {
printf("Invalid number of students.\n");
return 1;
}
for (int i = 0; i < studentCount; ++i) {
inputStudentData(&students[i], i);
}
const char* filename = "students.txt";
writeToFile(filename, students, studentCount);
readFromFile(filename);
return 0;
Subscribe to:
Post Comments (Atom)
Robust Structure
Robust Structure: Because it embodies the idea of developing systems or frameworks that are strong, stab...
-
XML Coding: The versatile and popular eXtensible Markup Language, or XML for short, is made to store and transfer d...
-
In CSS, the term “tags” is commonly used by beginners, but the correct term is selectors . CSS selectors are one of the most important p...
No comments:
Post a Comment