The main
function is where your program begins. The first thing you do when you program starts is:
cout << username;
This will immediately output the contents of the username
, which at the moment you have not filled with a username. Make sure you do the user input before you start outputting the username. This (if my psychic abilities are correct) will require calling the function you're defining in login.cpp. So whatever that function is called, call it: for example:
int main()
{
login();
cout << username << endl;
}
In your login.cpp file, you have this if-else statement without any enclosing function. I'm not sure if this just because you copied only part of the file, but those statements need to be within a function. You will probably need to declare that function in a header file if you want to use it in other files.
To share the username
global variable between different translation units you will need to declare it in a header file, as extern char username[50]
and then define it in only one of your implementation files as char username[50]
.
I, however, do not recommend using a global variable to this and suggest that you use std::string
instead of char
arrays. You can simply return
the username out of the login
function and do something like this:
int main()
{
std::string username = login();
std::cout << username << std::endl;
}
In reference to the comments on this post:
std::string login()
{
// Here we get the user's username and return it back to main
std::string username;
std::cin >> username;
return username;
}
void menu(std::string username)
{
std::cout << "Welcome " << username << std::endl;
}
int main()
{
std::string username = login(); // We receive the username from login()
menu(username); // We pass the username we received to menu()
}
emp_username
? And why do you have twochar username[50];
's?