pvjc20/du6/program.c

136 lines
2.8 KiB
C
Raw Normal View History

2020-04-17 08:45:14 +00:00
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<string.h>
#include<errno.h>
#include<inttypes.h>
intmax_t readMaxCount(char *buffer, int size);
bool readSttudent(char *buffer, int size);
int findIndex(char *array[], char *match, int count);
void swap(char **s1, char **s2);
void sort(char *array[], int size);
int main() {
char buffer[512];
char *sttudenti[1000];
int count = 0;
intmax_t maxCount = 0;
maxCount = readMaxCount(buffer, sizeof(buffer));
if (maxCount < 0) {
puts("Nespravny vstup");
return 0;
}
while (readSttudent(buffer, sizeof(buffer)) == true) {
char *sttudent;
int bl = strlen(buffer);
int l = (buffer[bl - 1] == '\n') ? (bl - 1) : bl;
if (l <= 0) {
continue;
}
sttudent = (char*) malloc(l + 1);
memcpy(sttudent, buffer, l);
sttudent[l] = '\0';
int index = findIndex(sttudenti, sttudent, count);
if (index > -1) {
free(sttudent);
continue;
}
sttudenti[count] = sttudent;
count++;
}
if (count == 0) {
puts("Ziadne prihlasky");
return 0;
}
sort(sttudenti, count);
puts("Prijati studenti:");
for (int i = 0; i < (maxCount > count ? count : maxCount); i++) {
puts(sttudenti[i]);
}
if (maxCount < count) {
puts("Neprijati studenti:");
for (int i = maxCount; i < count; i++) {
puts(sttudenti[i]);
}
}
for (int i = 0; i < count; i++) {
free(sttudenti[i]);
}
return 0;
}
intmax_t readMaxCount(char *buffer, int size) {
char *retValPtr = fgets(buffer, size, stdin);
int l = strlen(buffer);
if (retValPtr == 0 || ferror(stdin) != 0 || l == 0 || (l == 1 && buffer[0] == '\n')) {
return -1;
}
char *endPtr;
intmax_t result = strtoimax(buffer, &endPtr, 10);
2020-04-17 08:46:59 +00:00
if (errno == ERANGE || result == 0 || endPtr != buffer + (l - 1)) {
2020-04-17 08:45:14 +00:00
return -1;
}
return result;
}
bool readSttudent(char *buffer, int size) {
char *retValPtr = fgets(buffer, size, stdin);
int l = strlen(buffer);
if (retValPtr == 0 || ferror(stdin) != 0 || l == 0 || (l == 1 && buffer[0] == '\n')) {
return false;
}
return true;
}
int findIndex(char *array[], char *match, int count) {
for (int i = 0; i < count; i++) {
if (strcmp(array[i], match) == 0) {
return i;
}
}
return -1;
}
void swap(char **s1, char **s2) {
char *tmp = *s1;
*s1 = *s2;
*s2 = tmp;
}
void sort(char *array[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (strcmp(array[j], array[j + 1]) > 0) {
swap(&array[j], &array[j + 1]);
}
}
}
}