Hi have been struggling to understand how functions are working.
Have written the following code to try and pass a value to my function to print out Hello that number of times.
It is definitely passing the value to the function as it prints hello out that number of times however something is very wrong as what follows the 'hello's' is not pretty!!
I have a feeling it has something to do with my not having some kind of 'return' after my function code - but I have tried all types of different 'returns' to no avail - none seem to compile ----HELP!
I think I have missed something big - have read a couple of beginner pieces on functions but how to translate them into what i want to do, even the simplest thing seems to elude me.
You declare say_hello() to return a string to the calling function, but you don't
actually write a "return" statement in the function, so what it returns is undefined.
Then, on line 27, you print out that undefined garbage.
You want say_hello() to output something to the screen, but not return
something to the calling function, right? They are two different things.
// fun with functions
#include <iostream>
#include <string>
usingnamespace std;
void say_hello(int times)
{
while (times > 0)
{
string greeting;
greeting = "Hello! ";
cout << greeting;
times--;
}
}
int main ()
{
int in;
cout << "Enter the number of times you want it?\n";
cin >> in;
say_hello(in);
return 0;
}