Home > Mobile >  Counting number of words which starts with a given letter
Counting number of words which starts with a given letter

Time:12-01

I am a beginner and am making a program for counting how many words start with a given letter, I wrote a program that counts how many words starts with the letter A but can't make it to find using given letter - I tried making another variable ch and asking it from the user and verifying if *p == "ch" but it does not work

#include <stdio.h>
#include <string.h>
    
int main(void) 
{
    enum { N = 200 };
    char sentence[N];

    printf( "Enter sentence: " );
    fgets( sentence, N, stdin );

    size_t n = 0;

    for ( const char *p = sentence; *p; p  = strcspn( p,  " \t" ) )
    {
        p  = strspn( p, " \t" );
        if ( *p == 'A' )   n;
    }

    printf("No. of A in string \"%s\" is %zu\n", sentence, n );

    return 0;
}

The code that I tried:

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

int main(void)
{
    enum { N = 200 };
    char sentence[N];

    char ch;
    printf("Enter one char");
    scanf("%c", &ch);

    printf( "Enter sentence: " );
    fgets( sentence, N, stdin );

    size_t n = 0;

    for ( const char *p = sentence; *p; p  = strcspn( p,  " \t" ) )
    {
        p  = strspn( p, " \t" );

        if ( *p == ch )   n;
    }

    printf("No. of A in string \"%s\" is %zu\n", sentence, n );

    return 0;
}

CodePudding user response:

The problem is a classic one: scanf("%c", &ch); reads a single byte and leaves the newline in the stdin buffer, hence fgets( sentence, N, stdin ); reads the rest of the input line without waiting for further user input.

You should read the rest of the input line after the scanf() with:

int c;
while ((c = getchar()) != EOF && c != '\n')
    continue;

CodePudding user response:

You're making it much too complicated. I suggest something like this:

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

int isBlankSpace (char ch) {
  return (ch == ' ' || ch == '\t' || ch == '\n'); 
}

int main(void) {
    char sent[200], ch;
    printf("Enter a char: ");
    ch = getchar();
    getchar(); //gets newline character

    printf("Enter a sentence: " );
    fgets(sent,200,stdin); 

    int count = 0, i=0;
    while (i < strlen(sent)) {
      while (isBlankSpace(sent[i])) i  ; //successive blank spaces
      if ((i==0 || isBlankSpace(sent[i-1])) && sent[i] == ch) count  ; 
      i  ; 
    }

    printf("No. of words starting with %c's in the "\
          "string \"%s\" is %d\n", ch, sent, count);
    return 0;
}
  •  Tags:  
  • c
  • Related