-1

I know strchr only gets the first instance. But why is my loop not working. No matter how many times '.' or ' !' or '?' is used in the text. It keeps outputting 3.

 //this finds number of sentences
    int Y = 0;
    while (ch != '\0');
    if(strchr(text,'.') != NULL)
        Y++;
    if(strchr(text,'!') != NULL)
        Y++;
    if(strchr(text,'?') != NULL)
        Y++;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 4
    `while (ch != '\0');` is endless loop. (Tip: look at `;`) – KamilCuk Jun 08 '20 at 19:02
  • use braces. always. After a few years if you decide to not use braces in certain situations then fine, but for now, *always* `while (...) { if (...) { } }` – Ryan Haining Jun 08 '20 at 19:16
  • `strchr` does not loop. It returns a pointer to the match. If you want something to be incremented and used as a condition in a loop, you might want to take the value returned by strchr and increment it. – William Pursell Jun 08 '20 at 19:25

2 Answers2

2

For starters it seems there is a typo

while (ch != '\0');
                 ^^^ 

In any case this code snippet

int Y = 0;
while (ch != '\0');
if(strchr(text,'.') != NULL)
    Y++;
if(strchr(text,'!') != NULL)
    Y++;
if(strchr(text,'?') != NULL)
    Y++;

does not make sense because the search of target characters always start from the beginning of text.

The function strchr is not an appropriate function for this task if to use separate calls of the function for each target symbol.

In this case using this function you need three separate loops one for each target symbols.

Here is a demonstrative program that shows how the task can be performed using another string function strcspn.

#include <stdio.h>
#include <string.h>

size_t count_symbols( const char *s, const char *delim )
{
    size_t n = 0;

    while ( *s )
    {
        if ( *( s += strcspn( s, delim ) ) )
        {
            ++n;
            ++s;
        }           
    }

    return n;
}

int main(void) 
{
    const char *s = "Firt. Second? Third! That is all.";

    printf( "%zu\n", count_symbols( s, ".!?" ) );

    return 0;
}

The program output is

4
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
-2
size_t count(const char *haystack, const char *needle)
{
    size_t cnt = 0;

    while(*haystack)
    {
        if(strchr(needle, *haystack++)) cnt++;
    }
    return cnt;
}

int main(void)
{
    printf("%zu\n", count("Hwedgdf,.???,,,,.h.rtfdsg....dfsdgfs?gdfg//..? //.", ".?"));
}

https://godbolt.org/z/fLUsWz

0___________
  • 60,014
  • 4
  • 34
  • 74