I'm having some trouble figuring out why when I run the program it won't let me scan the character I want to search for. It just jumps straight to the last printf statement.
int main()
{
char s1[100], s2[100], s3[100], s4[100];
char character
char *charSearch[3] = {s1, s2, s3, s4};
int counter = 0;
int i;
printf("Enter 4 lines of text: \n");
scanf("%s %s %s %s", &s1, &s2, &s3, &s4);
printf("Enter a any character to search:\n");
scanf("%c", &character);
for(i = 0; i < 3; i++)
{
while(charSearch[i] = strchr( charSearch, character ))
{
counter++;
charsearch[i]++;
}
}
printf("Total occurrences of character %c is %d", character, counter);
return 0;
}
First things first, you declared an array of
char pointers
of size3
while giving it4
elements :char *charSearch[3] = {s1, s2, s3, s4};
This should be :
char *charSearch[4] = {s1, s2, s3, s4};
This declaration should also be done after scanning the contents of the 4char
array{s1,s2,s3,s4}
and not before.The name of any array is a
pointer
to its first element, thus when usingscanf()
withchar
arrays, you already pass the desired address by doing so :scanf("%s %s %s %s", s1, s2, s3, s4);
What you did here :
scanf("%s %s %s %s", &s1, &s2, &s3, &s4);
passed the address of the first address (sounds weird I know xD).There is also that irritating bug with
scanf("%c", &character);
which if you've previously scanned anything ending with anew line
, the character will take this\n
as its input. To over come this, it should be written as :scanf(" %c", &character);
Now to
strchr()
, this functions takes two parameters, achar
pointer
to a string and the character to search for in the string and it returns anotherchar
pointer
to the location of the character if it was found andNULL
otherwise.We'll need to do the following instead:
What it does is that at the beginning of each iteration of the
for
loop, it declares achar
pointer
and initialize it to the return value of thestrchr()
function. Then we loop while thispointer
is not equal toNULL
and in each iteration increment our counter and ourpointer
to make it pointing to the next character in the string.The final working version of your code should look like :