For part of my project I have to prompt the user to enter their name, number, and email address using a function. I wrote the code for the function but when I try to call it in main it doesn't work. I found that if I call the variables in main AND in the function it works, but I feel like that's not the right way to do it. And I can't make the variables global either.
1 2 3 4 5 6 7 8 9 10 11
void getInfo(string &, string &, string &)
{
string name, number, email;
cout << "Please enter your full name: ";
getline(cin, name);
cout << "Please enter you phone number: (ex. 555.555.5555) ";
getline(cin, number);
cout << "Please enter your email address: ";
getline(cin, email);
cout << endl;
}
Ill admit to having too many choices here. May be the nature of the simple task at hand, but choosing vector, std::array, tuple, struct, etc here I can't see much reason to pick one over another. Some of these lose the name of the individual pieces of data but I can't say that is a serious drawback. Just pick one for now, OP. Later, with more requirements, the choices may sort out cleaner.
#include <iostream>
#include <string>
void getInfo(std::string& name, std::string& number, std::string& email)
{
std::cout << "Please enter your full name: ";
std::getline(std::cin, name);
std::cout << '\n';
std::cout << "Please enter you phone number (ex. 555.123.4567): ";
std::getline(std::cin, number);
std::cout << '\n';
std::cout << "Please enter your email address: ";
std::getline(std::cin, email);
}
int main()
{
std::string name { };
std::string phone { };
std::string email { };
getInfo(name, phone, email);
std::cout << "\nname:\t" << name << "\nphone:\t" << phone << "\nemail:\t" << email << '\n';
}
Please enter your full name: Mork From Ork
Please enter you phone number (ex. 555.123.4567): 123.456.7890
Please enter your email address: b_will@reaper.org
name: Mork From Ork
phone: 123.456.7890
email: b_will@reaper.org