I am writing a function that replaces spaces with '-' (<- this character). I ultimately want to return how many changes I made.
#include <stdio.h> int replace(char c[]) { int i, cnt; cnt = 0; for (i = 0; c[i] != EOF; i++) if (c[i]==' ' || c[i] == '\t' || c[i] == '\n') { c[i] = '-'; ++cnt; } return cnt; } main() { char cat[] = "The cat sat"; int n = replace(cat); printf("%d\n", n); }
The problem is that it correctly changes the string to "The-cat-sat", but for n it returns 3 when it should return 2. What did I do wrong?
@ 4386427 suggested that this should be a different answer. @wildplasser has already provided a solution, this answer explains EOF and '\0'.
'\0'
EOF (EOF → End Of File). . . EOF , . , EOF , . . char char '\0', , , /. , , .
EOF
0
\0
-1
size_t
switch(){}
||
unsigned replace(char *cp){ unsigned cnt; for(cnt = 0; *cp ; cp++) { switch (*cp){ case ' ' : case '\t': case '\n': *cp = '-'; cnt++; default: break; } } return cnt; }
EOF, , , , - /.
for (i = 0; c[i] != EOF; i++)
EOF , , .
,
for (i = 0; c[i] != "\0"; i++)
#include <stdio.h> int repl(int c); int main(void){ int c, nc; nc =0; while ((c=getchar())!=EOF) nc = replc(c); printf("replaced: %d times\n", nc); return 0; } int replc(int c){ int nc = 0; for(; (c = getchar())!=EOF; ++c) if (c == ' '){ putchar('-'); ++nc; } else putchar(c); return nc; }