I am trying to write program, which take text and seperate it into sentences.
Input:
Hi, my name is John.
Output:
Hi,
my
name
is
John.
Code
int main ()
{
int str[200];
int i = 0;
puts ("Enter text. Do not forget to put dot at the end.");
do {
str[i] = getchar();
i++;
} while (str[i-1] != '.');
printf("\n");
int k, lenght = 0; //lenght -- the lenght of single word
for (i=0; str[i] != '.'; i++) {
if (str[i] == ' ' || str[i] == '.') {
printf ("\n");
k = i - lenght;
do {
putchar (str[k]);
k++;
} while (str[k] != ' ');
lenght = 0;
}
lenght++;
}
printf ("\n stop");
return 0;
}
If you try to run or if you can see, there is an error. It does not output last word.
I tried to put there this cycle:
do {
if (str[i] == ' ') {
printf("\n");
k=i-lenght;
do {
putchar(str[k]);
k++;
}while(str[k] != ' ');
lenght=0;
}
lenght++;
i++;
}while(str[i+1] != '.');
But its the same cycle... I also tried to make function:
void word (char *c,int index, int lenght ) {
printf ("\n");
int i = index - lenght;
do {
putchar (c[i]);
i++;
} while (c[i] != ' ');
return;
}
and I called it instead of do-while cycle (in the "if section " of the code):
for (i=0; str[i] != '.'; i++) {
if (str[i] == ' ' || str[i] == '.') {
word(str, i, lenght);
lenght = 0;
}
lenght++;
}
What surpriced me was, that the function was "outputting" only the firs Word in sentence. If the first word was "John" it output "John" "ohn" "hn".
So there is not just one question...
How to remake/repaire the cycle/function to output what I want - all of the words in the sentence?
Why it does not work? Well I know the answer - beacouse thy cycle is built to end on character ' ', but not the '.', but when I tried to change it, it output one more random character after dot.
Just please dont blame me for the code, I am just begginer trying to learn something. I know its not a Masterpiece and I can and I will make it shorter before I finish it.