1

This simple code counts number of sentences entered by checking period, question mark or exclamation mark. However, if I enter " ", it does not count sentences after space. How can I fix this?

int numberSentence(char ch[])
{
    int count=0, i=0;
    while(ch[i] != '\0')
    {
        if(ch[i] == '.' || ch[i] == '?' || ch[i] == '!')
            count++;
        i++;
    }

    return count;
}


int main()
{
    char ch[999];
    printf("Enter sentences:\n");
    scanf("%s", ch);
    printf("Number of sentences is %d", numberSentence(ch));

}
havada
  • 19
  • 1
  • 3

4 Answers4

2

Your problem lies at:

scanf("%s", ch)

scanf with "%s" will look until it finds a white-space, then storing the string into your pointer, ch.

In this case I would suggest using:

scanf("%c", ch)

Where it will scan character by character. You will need to slightly remodel the program.

Note that scanf() will return an integer representing the width of what it read. Thus:

while(scanf("%c", ch) == 1)
   if (ch == ...)
}

For your reference: http://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm

Matthew
  • 145
  • 11
1

If by blank you mean new line key, try:

if(ch[i] == '.' || ch[i] == '?' || ch[i] == '!' || ch[i] == '\n')
        count++;

but why not just use gets() instead?

while(gets(ch)!=NULL)
{
    count++;
}
Dr.Haimovitz
  • 1,568
  • 12
  • 16
1
#include <stdio.h>

int numberSentence(char ch[]){
    int count=0, i;
    char last = ' ';

    for(i = 0; ch[i]; ++i){
        if(ch[i] == '.' || ch[i] == '?' || ch[i] == '!'){
            count++;
            last = ' ';
        } else if(ch[i] == ' ' || ch[i] == '\t' || ch[i] == '\n'){
            continue;//white-space does't include to sentence of top.
        } else {
            last = ch[i];//check for Not terminated with ".?!"
        }
    }

    return count + (last != ' ');//+ (last != ' ') : +1 if Not terminated with ".?!"
}


int main(void){
    char ch[1000];

    printf("Enter sentences:\n");
    scanf("%999[^\n]", ch);//input upto newline
    printf("Number of sentences is %d", numberSentence(ch));
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
0

For this simple problem, you can let scanf() split your input on your sentence delimiters using the scanset conversion specifier.

#include <stdio.h>

int main(void) {
    int count = 0;
    char buf[1000];
    while (scanf("%999[^.!?]%*c", buf) == 1) ++count;
    printf("sentences: %d\n", count);
    return 0;
}

The %[^.!?] will scan all the data up to either a period, exclamation point or question mark. The %*c will scan past the punctuation without storing it (the * means there is no argument for the scanned input to be stored into).

jxh
  • 69,070
  • 8
  • 110
  • 193