#
#include <string>
#include <algorithm> // Required for std::sort
// Define the struct
struct Student {
int student_id;
std::string name_id;
};
// Helper function to compare two students by their ID (for sorting)
bool compareById(const Student& a, const Student& b) {
return a.student_id < b.student_id;
}
int main() {
const int MAX_STUDENTS = 5; // Changed limit to 5 students
Student students[MAX_STUDENTS]; // Fixed-size array
int actual_count = 0;
std::cout << "--- Enter Student Details (Max " << MAX_STUDENTS << ") ---\n";
std::cout << "Enter a negative ID to stop early.\n\n";
// 1. Input Loop (cin)
for (int i = 0; i < MAX_STUDENTS; ++i) {
std::cout << "Enter ID for student " << (i + 1) << ": ";
std::cin >> students[i].student_id;
if (students[i].student_id < 0) {
break;
}
std::cin.ignore(); // Clear newline buffer before getline
std::cout << "Enter Name for student " << (i + 1) << ": ";
std::getline(std::cin, students[i].name_id);
std::cout << "\n";
actual_count++;
}
// 2. Sorting Step
// std::sort needs the beginning of the array and the end of the populated elements
std::sort(students, students + actual_count, compareById);
// 3. View Results Loop (cout)
std::cout << "===================================\n";
std::cout << " SORTED RESULTS (BY ID ASC) \n";
std::cout << "===================================\n";
if (actual_count == 0) {
std::cout << "No student records to display.\n";
} else {
for (int i = 0; i < actual_count; ++i) {
std::cout << "ID: " << students[i].student_id
<< " | Name: " << students[i].name_id << "\n";
}
}
std::cout << "===================================\n";
return 0;
}

Tidak ada komentar:
Posting Komentar