Home > Mobile >  Comparing char in a string to another char in C
Comparing char in a string to another char in C

Time:12-05

what I have is a string that I get from txt file.

fgets(num_string, lenght, file);
num_string = "011110110101"

So than I select the first number and display it:

printf("Number: %c", num_string[0]);

After that my program gets all the numbers in string with this loop and it should then check each number if its 0 or 1:

for(j=0; j<=11; j  ){
                printf("numbers: %c\n", num_string[j]);

                if(strcmp(num_string[j], zero)==0){
                    num_of_zeros  ;
                    printf("\nNum of zeros: %d", num_of_zeros);
                }
                else{
                    num_of_ones  ;
                    printf("\nNum of ones: %d", num_of_ones);
                }
}

But the if statement does not want to work. Here is the problem that it writes in terminal:

AOC_2021_day_3.c: In function 'main':
AOC_2021_day_3.c:27:27: warning: passing argument 1 of 'strcmp' makes pointer from integer without a cast [-Wint-conversion]
                 if(strcmp(num_string[j], zero)==0){
                           ^~~~~~~~~~
In file included from AOC_2021_day_3.c:3:0:
c:\mingw\include\string.h:77:38: note: expected 'const char *' but argument is of type 'char'
 _CRTIMP __cdecl __MINGW_NOTHROW  int strcmp (const char *, const char *) __MINGW_ATTRIB_PURE;
                                      ^~~~~~

I would appreciate any help :D

CodePudding user response:

strcmp is for comparing to cstrings. In this case, you do not need strcmp at all. You want to check whether a specific character inside num_string is 0 or not. The if(strcmp(num_string[j], zero)==0) statement can be replaced with if(num_string[j] == '0').

  • Related