Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C, counting the number of blankspaces

Tags:

c

I'm writing a function that replaces blank spaces into '-' (<- 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, it correctly changes the string into "The-cat-sat" but for n, it returns the value 3, when it's supposed to return 2. What have I done wrong?

like image 790
SoSueat Avatar asked Oct 14 '17 15:10

SoSueat


1 Answers

@4386427 suggested this should be another answer. @wildplasser already provided the solution, this answer explains EOF and '\0'.

You would use EOF only when reading from a file (EOF -> End Of File). See this discussion. EOF is used to denote the end of file, and its value is system dependent. In fact, EOF is rather a condition than a value. You can find great explainations in this thread. When working with char array or a char pointer, it will always be terminated by a '\0' character, and there is always exactly one of those, thus, you would use it to break out of the loop when iterating through an array/pointer. This is a sure way to ensure that you don't access memory that is not allocated.

like image 85
Nik Avatar answered Oct 13 '22 16:10

Nik