forked from freudenreichan/info2Praktikum-Wortsalat
Kommetare ergaenzt
This commit is contained in:
1 parent
f8deef43e1
commit
24d344b17e
1 file changed
+18
-4
+18
-4
@@ -6,8 +6,11 @@
|
||||
// eine Funktion implementieren, die ein einzelnes Wort aus einer Textdatei (words.txt) einliest und als C-String zurückgibt.
|
||||
|
||||
// Read words from file and store in 'words' array
|
||||
|
||||
// Liest Wörter aus einer Textdatei und speichert sie im Array.
|
||||
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
|
||||
{
|
||||
// Prüft, ob die Eingaben gültig sind.
|
||||
if (file == NULL || words == NULL || maxWordCount == 0) {
|
||||
return 0;
|
||||
}
|
||||
@@ -18,38 +21,49 @@ int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
|
||||
int tooLong = 0;
|
||||
int ch;
|
||||
|
||||
while (count < maxWordCount && (ch = fgetc(file)) != EOF) {
|
||||
while (count < maxWordCount && (ch = fgetc(file)) != EOF) {
|
||||
// fgetc(file) liest jeweils ein Zeichen aus der Datei.
|
||||
|
||||
if (ch == ',' || ch == ';' || isspace((unsigned char)ch)) {
|
||||
if (ch == ',' || ch == ';' || isspace((unsigned char)ch)) {
|
||||
// isspace() erkennt Leerraumzeichen wie Leerzeichen und Zeilenumbrüche. Kommas und Semikolons werden separat geprüft.
|
||||
|
||||
// Speichert das Wort, wenn es nicht leer und nicht zu lang ist.
|
||||
if (length > 0 && !tooLong) {
|
||||
currentWord[length] = '\0';
|
||||
strncpy(words[count], currentWord, MAX_WORD_LEN);
|
||||
count++;
|
||||
strncpy(words[count], currentWord, MAX_WORD_LEN);
|
||||
// strncpy() kopiert das fertige Wort mit einer festgelegten maximalen Länge in das Zielarray.
|
||||
count++; // Erhöht die Anzahl der gespeicherten Wörter.
|
||||
}
|
||||
|
||||
// Setzt die Variablen für das nächste Wort zurück.
|
||||
length = 0;
|
||||
tooLong = 0;
|
||||
}
|
||||
else if (!tooLong) {
|
||||
|
||||
// Prüft, ob noch Platz für das Zeichen und '\0' vorhanden ist.
|
||||
if (length < MAX_WORD_LEN - 1) {
|
||||
// toupper() wandelt Kleinbuchstaben in Großbuchstaben um.
|
||||
// MAX_WORD_LEN - 1 Lässt Platz für '\0', das das Ende eines C-Strings kennzeichnet und verhindert, dass über den Wortpuffer hinausgeschrieben wird.
|
||||
currentWord[length] = (char)toupper((unsigned char)ch);
|
||||
length++;
|
||||
}
|
||||
else {
|
||||
// Überspringt das Wort, wenn es zu lang ist.
|
||||
tooLong = 1;
|
||||
length = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Speichert das letzte Wort, falls die Datei ohne Trennzeichen endet.
|
||||
if (count < maxWordCount && length > 0 && !tooLong) {
|
||||
currentWord[length] = '\0';
|
||||
strncpy(words[count], currentWord, MAX_WORD_LEN);
|
||||
count++;
|
||||
}
|
||||
|
||||
// Gibt die Anzahl der gespeicherten Wörter zurück.
|
||||
return (int)count;
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user