开发者

Program not working as well - C

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: ");
    mycha开发者_StackOverflowr = 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 !


This

int const count =0 ;    

and this

count++;

conflicts , value of const variable can't be changed (that is why it is called constant)


Replace

int const count = 0;

with

int count = 0;

Your are trying to change a variable (count++) declared const which, obviously, is not allowed.

EDIT: The answer to your updated question is that you should change the loop condition from string[i] == '\0' to string[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 for string[i] == '\0'. Therefore, your original loop didn't run a single time.


You cant change a constant, so int const count = 0; can't be modified by const++;, to solve it you just have to remove the const keyword:

 int count = 0;


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

This means run the loop for as long as string[i] == '\0', but string[i] can't also be mychar (unless mychar is \0) so you never increment count.

I think you meant:

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


Replace == with != in string[i] == '\0'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜