L. Doe L. Doe - 2 months ago 16
C++ Question

Writing a function that takes in an array of strings and returns a double, producing the average length of those strings

So I'm practicing for a test that is coming up, and I'm stumped on one of my questions. This is a two part question, I'll include both questions first.

1) Create a function that takes in an array of strings and returns a double. This double will represent the average length of all the strings.

2) Create a MAIN function that asks the user for 10 strings. Once the array is filled, call the function from Question 1 to calculate the average length of the strings and output the result to the console.

Here is my code so far:

void avg(std::string averages[], int size) {

double sum = 0;

for(int index = 0; index < size; index++) {

sum += averages[index]; // Error here, invalid operands to binary expression?

}

double retVal = sum / size;
return retVal; //**I am getting an error here: void function avg should not return a value

}

int main() {

std:: string myArray[10];
std:: cout << "Please enter 10 strings...";

for(int i = 0; i < 10; i++) {
std::cin >>myArray[i];

}

}

Answer

sum is an integer. You have defined averages as an array of strings; you can't add strings to integers. Try

sum += averages[index].length();

Also, your comment later "I am getting an error here: void function avg should not return a value"... well the error message is telling you exactly what the problem is; your function is defined as

void avg(std::string averages[], int size) {
...
}

The type declared before the function name is its 'return type'. The keyword 'void' simply means 'this function doesn't return a value', so it is then getting confused when you try to use the return keyword to actually return a value. Change it to

double avg(std::string averages[], int size) {
...
}

Edit

To call the function, your main() should look like this. I've not tested this but it should work.

int main() {
   std::string myArray[10];
   std::cout << "Please enter 10 strings...\n";

   for(int i = 0; i < 10; i++) {
      std::getLine(std::cin, myArray[i]);
   }

   std::cout << avg(myArray, 10) << "\n";
}