Home > database >  I can't print the first index of the Character Array?
I can't print the first index of the Character Array?

Time:02-05

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

int main()
{
    char A[100];
    char c;
    scanf("%s", &A);
    while ((getchar()) != '\n');
    scanf("%c", &c);
    int i, count = 0;
    for(A[i] = 0; A[i] != c; i  ) {
        count  ;
    }
    //printf("%d",count);
    for(i = 0; i < count; i  ) {
        printf("%c", A[i]);
    }
    return 0;
}

I want to print (ca) if I enter input String A as (cat) and character c as (t ).But I am getting output as (a) the first word is not printing .Please tell me what is wrong with my code.

CodePudding user response:

for(A[i] = 0; A[i] != c; i  ) 

This assigns 0 to the first position in A (A[i] = 0). You probably wanted to write

for(i = 0; A[i] != c; i  ) 

instead.

There are some other problems with the code as well, especially in error handling, but I'll let you figure those out.

CodePudding user response:

Well, what does the compiler say? Assuming your program is stored in test.c:

$ gcc -Wall test.c
test.c: In function ‘main’:
test.c:8:13: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[100]’ [-Wformat=]
    8 |     scanf("%s", &A);
      |            ~^   ~~
      |             |   |
      |             |   char (*)[100]
      |             char *
test.c:12:14: warning: ‘i’ is used uninitialized in this function [-Wuninitialized]
   12 |     for(A[i] = 0; A[i] != c; i  ) {
      |         ~~~~~^~~
  •  Tags:  
  • c
  • Related