C, Reading and Identifying Sentences

2019-09-23 16:20发布

问题:

what I am trying to do is take an input file such as..

Hello. This is my test file. How many sentences are in this?
Hopefully the program will work! Good luck.

And need it to print out each individual sentence along and number them like so..

1. Hello.
2. This is my test file.
3. How many sentences are in this?
4. Hopefully the program will work!
5. Good luck.

Here is my code so far, I am attempting this in C but I also briefly thought maybe I should be doing this in bash instead? I'm not sure..

Here is what I have so far, but is not working.

#include <stdio.h>
#include <stdlib.h>

main()
{
int storage[50];
int i;
char c;
for(;;){
    while (c!= '.' && c!= '!' && c!= '?'){
    c=getchar();
    c=storage[i];
    i++;
    if (c == '.' || c == '!' || c == '?'){
        for(i=i; i!=0; i--){
            printf("%s", storage[i]);
        }
    }
    }

}
}

回答1:

int i; here variable i is not initialized meaning it can have any value more than 50 where you are trying to store into c which is not expected.

c doesn't have contains proper value anything in which you checking its contents in while loop which fails looping in for.

I suggest you perform a open a your file using fopen. Start reading line by line using fgets into a buffer and then operate on it using strtok() by delimiter as space ' ' to break the string after every space and continue.



回答2:

This is approximately what you want. Note that there is still room for improvements. For example it doesn't skip the space after the '?', '.' or '!', it processes only one line, the maximum number of letters in a phrase is 50, if you type a phrase with more that 50 letters the storage buffer will silenty overflow.

void main()
{
  int storage[50];
  int i = 0 ;
  int linecount = 1 ;
  char c;

  for (;;)
  {
    c=getchar();

    if (c == '\n')
      break ;

    storage[i] = c;
    i++;

    if (c == '.' || c == '!' || c == '?')
    {
      int j ;

      printf("%d. ", linecount++);

      for (j = 0; j < i; j++)
      {
        printf("%c", storage[j]);
      }

      i = 0 ;
      printf("\n");
    }
  }
}


标签: c io