neue Lösung von input.c

This commit is contained in:
greinerno105857 committed 2026-10-22 10:50:58 +02:00
1 parent 61193c20ab
commit efd28dec07
1 file changed
+34 -47
+34 -47
View File
@@ -2,57 +2,44 @@
#include <string.h> #include <string.h>
#include <ctype.h> #include <ctype.h>
// TODO: // Liest ein einzelnes Wort aus der Datei in 'buffer' (max. bufferSize Zeichen inkl. '\0')
// eine Funktion implementieren, die ein einzelnes Wort aus einer Textdatei (words.txt) einliest und als C-String zurückgibt. // Gibt 'buffer' zurück oder NULL, wenn kein Wort mehr vorhanden ist
int splitWords(char texRow[], int maxLength, int wordNumber, char words[][MAX_WORD_LEN], unsigned int maxWordCount); static char *readWord(FILE *file, char *buffer, unsigned int bufferSize)
// Read words from file {
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) int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
{ {
char word[MAX_WORD_LEN];
unsigned int wordCount = 0;
// Datei Zeilenweise auslesen while (wordCount < maxWordCount && readWord(file, word, MAX_WORD_LEN) != NULL)
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)
{ {
if (row < maxWordCount) strncpy(words[wordCount], word, MAX_WORD_LEN - 1);
{ words[wordCount][MAX_WORD_LEN - 1] = '\0';
strncpy(words[row], token, maxStringLength); wordCount++;
words[row][maxStringLength - 1] = '\0';
row++;
}
} }
while (token != NULL && row < maxWordCount) return wordCount;
{ }
token = strtok(NULL, teiler);
if (token != NULL)
{
strncpy(words[row], token, maxStringLength);
words[row][maxStringLength - 1] = '\0';
row++;
}
}
return row;
}