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 pointersof size3while giving it4elements :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 4chararray{s1,s2,s3,s4}and not before.The name of any array is a
pointerto its first element, thus when usingscanf()withchararrays, 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\nas its input. To over come this, it should be written as :scanf(" %c", &character);Now to
strchr(), this functions takes two parameters, acharpointerto a string and the character to search for in the string and it returns anothercharpointerto the location of the character if it was found andNULLotherwise.We'll need to do the following instead:
What it does is that at the beginning of each iteration of the
forloop, it declares acharpointerand initialize it to the return value of thestrchr()function. Then we loop while thispointeris not equal toNULLand in each iteration increment our counter and ourpointerto make it pointing to the next character in the string.The final working version of your code should look like :