From efd28dec07a74d1aa8685291ed9b7120fe195af0 Mon Sep 17 00:00:00 2001 From: Noah Date: Thu, 22 Oct 2026 10:50:58 +0200 Subject: [PATCH] =?UTF-8?q?neue=20L=C3=B6sung=20von=20input.c?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Startcode/input.c | 81 ++++++++++++++++++++--------------------------- 1 file changed, 34 insertions(+), 47 deletions(-) diff --git a/Startcode/input.c b/Startcode/input.c index 13992f3..4bc24fb 100644 --- a/Startcode/input.c +++ b/Startcode/input.c @@ -2,57 +2,44 @@ #include #include -// TODO: -// eine Funktion implementieren, die ein einzelnes Wort aus einer Textdatei (words.txt) einliest und als C-String zurückgibt. -int splitWords(char texRow[], int maxLength, int wordNumber, char words[][MAX_WORD_LEN], unsigned int maxWordCount); -// Read words from file +// Liest ein einzelnes Wort aus der Datei in 'buffer' (max. bufferSize Zeichen inkl. '\0') +// Gibt 'buffer' zurück oder NULL, wenn kein Wort mehr vorhanden ist +static char *readWord(FILE *file, char *buffer, unsigned int bufferSize) +{ + unsigned int len = 0; + int c = fgetc(file); + // Trennzeichen (Leerzeichen, Komma, Semikolon, Zeilenumbruch, ...) überspringen + while (c != EOF && !isalpha(c)) + c = fgetc(file); + + // Buchstaben sammeln, bis ein Trennzeichen oder das Dateiende kommt + while (c != EOF && isalpha(c)) + { + if (len < bufferSize - 1) + buffer[len++] = toupper(c); + c = fgetc(file); + } + + buffer[len] = '\0'; + + if (len == 0) + return NULL; + return buffer; +} + +// Read words from file and store in 'words' array int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount) { + char word[MAX_WORD_LEN]; + unsigned int wordCount = 0; - // Datei Zeilenweise auslesen - char textRow[MAX_LINE_LEN]; - int row = 0; - - while (fgets(textRow, MAX_LINE_LEN, file) != NULL) - row = splitWords(textRow, MAX_LINE_LEN, row, words, maxWordCount); - - fclose(file); - - for (int i; i < row; i++) - printf("%s\n", words[i]); - - return row; -} - -// Zeilen in lesbare Wörter aufteilen und "words" zuweisen -int splitWords(char textRow[], int maxStringLength, int row, char words[][MAX_WORD_LEN], unsigned int maxWordCount) -{ - char *teiler = " .,\n;"; - char *token = strtok(textRow, teiler); - - if (token != NULL) + while (wordCount < maxWordCount && readWord(file, word, MAX_WORD_LEN) != NULL) { - if (row < maxWordCount) - { - strncpy(words[row], token, maxStringLength); - words[row][maxStringLength - 1] = '\0'; - row++; - } + strncpy(words[wordCount], word, MAX_WORD_LEN - 1); + words[wordCount][MAX_WORD_LEN - 1] = '\0'; + wordCount++; } - while (token != NULL && row < maxWordCount) - { - - token = strtok(NULL, teiler); - - if (token != NULL) - { - strncpy(words[row], token, maxStringLength); - words[row][maxStringLength - 1] = '\0'; - row++; - } - } - - return row; -} + return wordCount; +} \ No newline at end of file