The following code gives me a zero value for ‘count’ all the time…
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 128
int main ()
{
char mychar , string [SIZE];
int i;
int 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;
}
Thanks !
Replace
with
Your are trying to change a variable (
count++) declaredconstwhich, obviously, is not allowed.EDIT: The answer to your updated question is that you should change the loop condition from
string[i] == '\0'tostring[i] != '\0'. This is because the loop runs while the condition is true.string[i] != '\0'is true for the whole string except the terminating null byte while the opposite is true forstring[i] == '\0'. Therefore, your original loop didn’t run a single time.