Hello bstroe,
The first 2 things you need to do is post the instructions that you were given, so that everyone will know what you have to do along with what you can use and can not use.
Next it is best to post a whole program that can be compiled and tested. A large program can be cut down to enough to demonstrate your problem.
If using a "std::string" is not an option then consider the function"strtok()"
https://en.cppreference.com/w/c/string/byte/strtok to break up the whole string into individual tokens, or words in this case.
If you can use the header file "<cctype>", or "<ctype.h>" you will have the function "isalpha()"
https://en.cppreference.com/w/c/string/byte/isalpha There are others for numbers and punctuation. This could eliminate the "is_letter" function or enhance it.
With out further input I do not know if numbers and punctuation are not to be counted in a word.
Last I have to say the some blank lines and proper indentation would make youe code easier to read. As an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
int is_letter(char c)
{
if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))
{
return 1;
}
return 0;
}
int nr_words(char s[101])
{
int n = strlen(s);
int i_have_words = 0;
int nr_words = 0;
for (int i = 0; i < n; i++)
{
if (is_letter(s[i]))
{
i_have_words = 1;
}
else if (i_have_words == 1)
{
nr_words++;
i_have_words = 0;
}
}
if (i_have_words == 1)
{
++nr_words;
}
return nr_words;
}
int main()
{
// ifstream fin("date.in");
// <--- if used HOW do you know if the stream is open. Or is it that you have not written that code yet?
char s[101];
cin.getline(s, 101);
char len = strlen(s); // <--- Defined as a "char", but "strlen()" returns a "size_t". This may work, but could be a better type.
double average_length_words = len / nr_words(s);
cout << fixed << setprecision(2) << average_length_words;
}
|
Just a suggestion, but one you should pay attention to.
Andy