From 8b9d9bd62da2b7ff46a194a6c59f3b315e7ce34c Mon Sep 17 00:00:00 2001 From: paulusja Date: Thu, 20 Nov 2025 13:01:43 +0100 Subject: [PATCH] Add solution for const-assignment. --- 07_const/const.c | 70 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 4 deletions(-) diff --git a/07_const/const.c b/07_const/const.c index aaa7d32..2e3f4d7 100644 --- a/07_const/const.c +++ b/07_const/const.c @@ -16,8 +16,9 @@ #define PUFFER_GROESSE 100 -char *gibTextEin(char *ausgabeText, char *puffer, unsigned int groesse); -void gibSummeAus(unsigned int zahlen[], unsigned int anzahl); +char *gibTextEin(const char *ausgabeText, char *puffer, unsigned int groesse); +void gibSummeAus(const unsigned int zahlen[], unsigned int anzahl); +unsigned int konvertiereZahlen(const char *text, unsigned int zahlen[], unsigned int maxZahlen); int main() { @@ -34,7 +35,7 @@ int main() return EXIT_SUCCESS; } -char *gibTextEin(char *ausgabeText, char *puffer, unsigned int groesse) +char *gibTextEin(const char *ausgabeText, char *puffer, unsigned int groesse) { printf("%s", ausgabeText); fgets(puffer, groesse, stdin); @@ -47,7 +48,68 @@ char *gibTextEin(char *ausgabeText, char *puffer, unsigned int groesse) return puffer; } -void gibSummeAus(unsigned int zahlen[], unsigned int anzahl) +// 1. Variante mit strtok (zahl steht separat) und a) sscanf oder b) stroul +// unsigned int konvertiereZahlen(const char *text, unsigned int zahlen[], unsigned int maxZahlen) +// { +// unsigned int anzahl = 0; +// char *kopie = malloc((strlen(text)+1) * sizeof(char)); + +// if(kopie != NULL) +// { +// const char *trenner = " \t;,.:\n"; +// char *token; + +// strcpy(kopie, text); + +// token = strtok(kopie, trenner); + +// while(token != NULL && anzahl < maxZahlen) +// { +// //if(sscanf(token, "%u", &zahlen[anzahl]) == 1) +// // anzahl++; +// char *endZgr; + +// zahlen[anzahl] = strtoul(token, &endZgr, 10); + +// if(token != endZgr) +// anzahl++; + +// token = strtok(NULL, trenner); +// } + +// } + +// free(kopie); + +// return anzahl; +// } + +// 2. Variante direkt mit strtoul (Zahl ist nahtlos in String integriert) +unsigned int konvertiereZahlen(const char *text, unsigned int zahlen[], unsigned int maxZahlen) +{ + unsigned int anzahl = 0; + const char *anfangsZgr = text; + char *endZgr; + + while(anzahl < maxZahlen && *anfangsZgr != '\0') + { + zahlen[anzahl] = strtoul(anfangsZgr, &endZgr, 10); + + if(endZgr != anfangsZgr) + { + anfangsZgr = endZgr; + anzahl++; + } + else + { + anfangsZgr++; + } + } + + return anzahl; +} + +void gibSummeAus(const unsigned int zahlen[], unsigned int anzahl) { int summe = 0;