I have this program below that I have been working on, given for you advanced programmers this is probably cake, but my whole CS 1 class has struggled with it. I have it working except that unless I include a space after the last word of the string, then it won't register the last word. In the comments I have the whole problem that we got asked and have a pretty poorly mad algorithm, but the program is what I'm worried about. Please suggest what you can and please remember its a CSCI 261 class (Computer Science 1) and this is my first programming class. Thanks for your help in advance!
Code:
/*
Write a program that processes a sequence of lines, displaying a count of the total number of words in those lines as well as counts of the number of words with one letter, two letters, and so on.
Have the user input the sentences.
Enter a for statement that checks for spaces
When the for statement finds a space it will break the word up from the rest of the sentence
I have predetermined there will be 5 words being less than or equal to five characters long
It will then enter a if statement to calculate how many words have how many letters done by adding 1 to the number of letters (ex one=one+1)
Return to the user how many words there are and how many words have each number of letters.
Stop.
*/
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#define stringlength 50
char string1[stringlength];
char string2[stringlength];
char string3[stringlength];
char string4[stringlength];
char string5[stringlength];
int one=0, two=0, three=0, four=0, five=0;
int i, index, word=0;
char count(char *);
int
main(void)
{
printf("Please enter sentences less than 50 letters with words being no longer than 5 letters.\nPlease use no punctuation and to go on to the next sentence hit enter\n");
gets(string1);
gets(string2);
gets(string3);
gets(string4);
gets(string5);
count(string1);
count(string2);
count(string3);
count(string4);
count(string5);
printf("The string consists of:\nWords: %d\n1 Letter words: %d\n2 Letter words: %d\n3 Letter words: %d\n4 Letter words: %d\n5 Letter words: %d\n", word, one, two, three, four, five);
return(0);
}
char count (char string[])
{
char word1[5];
int index;
for(i=0; i < strlen(string); i=i+1)
{
if(string[i]==' ' || string[i]=='\n' || string[i]=='\0')
{
word=word+1;
index=i;
strncpy(word1, string, index);
if(index==1)
one = one + 1;
else if(index==2)
two = two + 1;
else if(index==3)
three = three + 1;
else if(index==4)
four = four + 1;
else if(index==5)
five = five + 1;
strcpy(string, &string[index+1]);
i=0;
}
}
return(one, two, three, four, five, word);
}