Portál AbcLinuxu, 1. května 2025 00:44
#include <stdio.h> #include <string.h> #include <ctype.h> #define myupper(c) ((c) >= 'A' && (c) <= 'Z') enum { MAX = 100 }; int main() { int uppermacro(char *str); int ctypefun(char *str); char str[MAX]; int nupper; while (fgets(str, MAX, stdin) != NULL) { if (str[strlen(str) - 1] == '\n') str[strlen(str) - 1] = '\0'; nupper = uppermacro(str); printf("upper macro: %d\n", nupper); nupper = ctypefun(str); printf("ctype function: %d\n", nupper); } return 0; } int uppermacro(char *str) { int nupper = 0; while (*str != '\0') { if (myupper(*str++)) nupper++; } return nupper; } int ctypefun(char *str) { int nupper = 0; while (*str != '\0') { if (isupper(*str++)) nupper++; } return nupper; } /* while (myupper(c = getchar())) ... ERROR while (isupper(c = getchar())) ... WORKS while ((c = getchar()) != EOF && isupper(c)) ... SAFER */Takový blog sem ještě patří?
Tiskni
Sdílej:
if (str[strlen(str) - 1] == '\n') str[strlen(str) - 1] = '\0';Lebo:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.
echo -e "123456"|./check_end_fgets 49 '1' 50 '2' 51 '3' 0 ''Testovací kód:
#include <stdio.h> #include <stdlib.h> void check_end_fgets() { char buffer[4]; int a; char *p; if(fgets(buffer, 4, stdin) == NULL) return; for(p=buffer,a=0;a<4 && *p != '\n'; a++,p++) printf("%d '%c'\n", *p, *p); } int main(void) { check_end_fgets(); return 0; }
echo "LLLLLLLLLLLLLL"|./cod upper macro: 7 ctype function: 14Oprav si chybu vo funkcií uppermacro().
((*str++) >= 'A' && (*str++) <= 'Z')
getc()
upozornění, že na rozdíl od fgetc()
může být implementována jako makro, které argument vyhodnocuje víc než jednou.
cpp source.c -o source_cpp.h
#define myupper(c) ((c) >= 'A' && (c) <= 'Z')
se dá nahradit něčim jako
#define myupper(c) ((unsigned long)(c - 'A') <= 'Z' - 'A')
(ale je to trochu prasárna)
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.