Search code examples
cgcccompilationgets

gets() problem in C


I wrote the following code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int const count =0 ;    

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}

The problem is that the gcc gives me an error for the 'int const count': " increment of read-only variable ‘count’".

What seems to be wrong ?

Thank !


Solution

  • Try using fgets instead as:

    fgets (string, SIZE, stdin);
    

    Why gets is unsafe, has been answered several times on SO. You can see this.