Hello Zii,
In answer to your question. Your code would work better as:
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
|
#include <iostream>
#include <string> // <--- Need this header file for the strings.
//using namespace std; // <--- Best not to use.
// The most recent post that is worth reading. http://www.cplusplus.com/forum/beginner/258335/
using std::cin;
using std::cout;
using std::endl;
using std::string;
// Prototypes.
void SayHello(string name);
int main()
{
std::string name;
std::cout << "\n Enter your name: ";
std::getline(cin, name);
SayHello(name);
return 0; // <--- Not required, but makes a good break point.
}
void SayHello(string name)
{
cout << "\n Hey there, " << name << endl;
}
| |
I did rearrange the program to make some points that you may not be aware of.
First off lines 12 and 26 must match. /this means that the return type and parameters must match. For the parameters they must match in type and order. I find that writing the function definition and copying that to paste in for the prototype works the best. Notice the only difference between the prototype and function definition is the (;) at the end of the prototype.
For a prototype only the variables' type is required, but I find including the variables' name helpful.
The function call, line 21, is slightly different only the variables' name is required the type is not.
I added line 18 because you need a prompt to let the user know what needs to be entered. In the end what you say is your choice, but I would suggest ending the prompt with
name: ";
. The final space helps and the lack of a "\n" or "endl" puts the "cin" on the same line. I just think it looks nicer this way.
Because you are entering a name I used "std::getline" from the "string" header file. This will put whatever you type into the "name" variable whereas the formatted input,
cin >> name;
will stop at the first white space or new line whichever comes first. So given a name like "First Last" only "First" will be put in "name" and "Last" will be left in the input buffer for the next "cin" to deal with.
I do not know if you are aware of the difference between pass by value and pass by reference, but
keskiverto's program is a very good example.
Andy