-
simple functions
we are starting to learn about functions now and we have a simple function that we have to do. i was looking through my book, but all the examples were using int and not string (which is what i think i need).
the description of the problem is: Write a function called myName which returns (does not cout) your full name (e.g., "Bob Smith"). Write main to call the function and display the name on the screen. NOTE: Your name should not appear anywhere other than in the function myName.
so far i have something looking like this:
Code:
#include <iostream>
#include <string>
using namespace std;
string myName()
{
return "users name";
}
int main()
{
myName;
}
i know this is a very short and simple program but im not sure if im on the right track.
thanks for the help.
-
You are on the right track, but you need to actually call the function and print the string returned.
-
what are you referring to when you say i need to 'call' the function? and how will i be able to print the string returned without cout? (i am assuming that the 'return' command has something to do with this).
-
To call a function, you must use paranthesises - myfunction().
Then you need to assign the return to a variable in main to print it out later.
It's the same way with integers.
You are on the correct path.
-
Here's what I would do, in pseudo code, so you can learn from it:
Code:
#include <iostream>
#include <string> //Use this for strings
using namespace std; //Makes it so you don't have to use std:: in front of a ton of commands
//Declare function prototype
string functionname(function arguments);
//The arguments are what it brings in. You'll use void there, I think
int main(){
declare a string;
string = functionname(); //That calls the function, and the string equals whatever it returns (a string)!
cout their name;
wait for a key to be pressed - Do not use system("pause")!!!
return 0 to main();
}
string functionname(arguments){
declare a string;
Ask for their name;
Get their name - getline(cin, stringname); //Where stringname is the string that the text goes into
return the string to main()
}
Cheers
-
the only thing is that the user isnt entering their name. its a program that we have to write which when we run it, our name just automatically comes up. also, we arent supposed to use cout. the professor said that these next few assignments should be really quick if we understand what we are doing... and apparently i dont. hah.
thanks again.
-
You're quite close. You just need to add a few things. "cout" will be used in main to display the return value of the function. I think your teacher meant don't use "cout" within the function that is returning your name. So I'm sure it's fine to use it in main().
Code:
#include <iostream>
#include <string>
using namespace std;
string myName()
{
return "users name";
}
int main()
{
cout << myName(); //This will print the return value of the function. In this case, users name
return 0;
}