Hi, I'm trying to create a function that works in a way like a void, where you have to call it for it to execute but I found that you can't return in a void, here's what I was HOPING to do...
void output( int i )
{
if( i == 5 )
std::cout << "Hello world!" << std::endl;
elseif( i < 5 )
output( i + 1 );
else //i > 5
output( i - 1 );
}
//another way to do the same function:
void ouptut( int i )
{
if( i != 5 )
{
while( i < 5 )
++i;
while( i > 5 )
--i;
}
std::cout << "Hello world!" << std::endl;
}
Though these probably aren't the most practical examples but hopefully you get the idea.
//Register Username
cout << "Please enter a username." << endl;
cin >> sRegisterUsername;
if ( sRegisterUsername.size() >= 20 )
{
cout << "Username can't be more than 20 characters long." << endl;
return CallCommandRegister();;
}
elseif ( sRegisterUsername.size() <=5 )
{
cout << "Username can't be less than 5 characters long." << endl;
return CallCommandRegister();
}
else
{
cout << "Username: " << sRegisterUsername << " successful." << endl;
}
But the problem that I face now is how would I create sections within that void? So I have a Register username section and a Register password section within that void. Is there a way to split those sections up so that when I come to return an error I can do something like
Well you could certainly write functions called RegisterUsername() and RegisterPassword() and call them from within your CallCommandRegister() function.
Instead of using recursion, you could use a while loop to keep asking the user for a username/password until successful:
// Asks the user to register a username and checks to make sure the length is correct
void RegisterUsername()
{
bool registered = false;
while (registered != true)
{
string sRegisterUsername
cout << "Please enter a username." << endl;
cin >> sRegisterUsername;
if ( sRegisterUsername.size() >= 20 )
{
cout << "Username can't be more than 20 characters long." << endl;
}
elseif ( sRegisterUsername.size() <=5 )
{
cout << "Username can't be less than 5 characters long." << endl;
}
else
{
cout << "Username: " << sRegisterUsername << " successful." << endl;
registered = true;
}
}
}
void RegisterPassword()
{
// Similar code goes here.
}
void CallCommandRegister()
{
RegisterUsername();
RegisterPassword();
}
Of course, from here you could do all sorts of fancy things, like keeping track of how many tries the user makes to register and then exiting. You could even return the value of the username and password and display them at the end of CallCommandRegister(), but I'll let you figure that one out. :)