C counting the number of spaces

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?

+6
source share
4 answers

@ 4386427 suggested that this should be a different answer. @wildplasser has already provided a solution, this answer explains EOF and '\0'.

EOF (EOF → End Of File). . . EOF , . , EOF , . . char char '\0', , , /. , , .

+1
  • 0 (), EOF (: \0, -1 - , UB, )
  • [sylistic] ( C)
  • [] "i".
  • [stylistic] : . ( size_t, )
  • [] a 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;
}
0

EOF, , , , - /.

for (i = 0; c[i] != EOF; i++)

EOF , , .

,

for (i = 0; c[i] != "\0"; i++)
0
source
#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;
}
0
source

All Articles