Reputation: 21
I am very confused as to what kind of variables I would put into my function here: names. I am doing a practice problem in a C++ book, because I am learning C++ and am on References and pointers right now, and cannot find a solution.
Just for background information, the problem asks:
Write a function that prompts the user to enter his or her first name and last name, as two separate values.
This function should return both values to the caller via additional pointer(or reference) parameters that are passed to the function.
Try doing this first with pointers and then with references.
#include <iostream>
#include <string>
#include <istream>
using namespace std;
struct someStruct{
string firstname;
string lastname;
};
void names(someStruct &firstname, someStruct &lastname) {
cout << "First Name: " << "\n";
cin >> firstname.firstname;
cout << "Last Name: " << "\n";
cin >> lastname.lastname;
// I was just curious is adding firstname to firstname would work... and it did
cout << lastname.lastname << ", " << firstname.firstname;
cin.get();
}
int main() {
names();
// I don't know what to put here, above, as parameters
cin.get();
}
Upvotes: 0
Views: 68
Reputation: 1
Your code makes no sense, why are you passing someStruct
twice?
For the reference part, you should have something like:
void names(someStruct &s) { // <<<< Pass struct once as a reference
cout << "First Name: " << "\n";
cin >> s.firstname;
cout << "Last Name: " << "\n";
cin >> s.lastname;
}
and in main()
:
int main() {
someStruct x; // <<<< Create an instance of someStruct
names(x); // <<<< Pass it as parameter
cout << "Input was: firstName = " << x.firstname
<< ", lastName = " << x.lastname
<< endl;
cin.get();
}
For the pointer part, you should have something like:
void names(someStruct *s) { // <<<< Pass struct once as a reference
cout << "First Name: " << "\n";
cin >> s->firstname;
// ^^ Note the difference in dereferencing
cout << "Last Name: " << "\n";
cin >> s->lastname;
// ^^ Note the difference in dereferencing
}
and in main()
:
int main() {
someStruct x; // <<<< Create an instance of someStruct
names(&x); // <<<< Pass the address of x as parameter
// ^ Note the addess-of operator here
cout << "Input was: firstName = " << x.firstname
<< ", lastName = " << x.lastname
<< endl;
cin.get();
}
Upvotes: 1