#include <iostream>
#include <cstring>
usingnamespace std;
int findWhitespace(char[]);
double findAve(char[], int);
int main()
{
//modified version of Program 12-2...
constint LENGTH = 80;
char line[LENGTH];
cout << "Enter a sentence of no more than ";
cout << LENGTH - 1 << " characters: " << endl;
cin.getline(line, LENGTH);
if (line[0] == ' ' || line[0] == '\0')
{
cout << "Invalid sentence..." << endl;
cout << "Enter a sentence of no more than ";
cout << LENGTH - 1 << " characters: " << endl;
cin.getline(line, LENGTH);
}//end of if
int a = findWhitespace(line);
cout << endl << "The sentence has ";
cout << a << " words in it." << endl;
cout << "Average letters per word " << findAve(line, a) << endl;
}//end of main
int findWhitespace(char c[])
{
int n = 1;//for the first word...
for (int i = 0; c[i] != '\0'; i++)
{
if (c[i] == ' ')
{
n++;
}
}
return n;
}//end of findWhitespace
double findAve(char c[], int words)
{
int num, index = 0, letters[words];
double total, ave;
for (int j = 0; c[j] != '\0'; j++)
{
if (c[j] != ' ' || c[j] != '.') {
num++;
} else {
letters[index] = num;
index++;
total += letters[j];
}
}
ave = total / words;
return ave;
}//end of findAve
What are you trying to average? Why are you trying to use variables before they are initialized? Where do you actually assign any values tour letters array?
IMO your findAve() function has several major problems. One of the biggest problems is that you're using at least one variable that hasn't been initialized.
Next you're using a VLA in your function, VLA are not allowed in C++ programs. Array sizes must be compile time constants.
Next the use of this array seems inconsistent. You add a value to letters[index] but you "count" letters[j]. These two indexes are not necessarily the same value.
No, it is actually better to create variables inside functions unless the variable contains a value from outside of the function. In your function above you only need to pass the character array since the other two variables are only used inside this function.
A VLA is a Variable Length Array which are only guaranteed to be supported in C99 programs. These constructs allow the creation of arrays with run time sizes. In C++ the alternative is to use a std::vector.
We were doing c-strings this week in class so we couldn't use anything we wanted to on the homework. This assignment was supposed to modify the one that came before it.
A lot of the code I see online doesn't use usingnamespace std; and uses the scope resolution operator on everything. Is that a better standard?