-
Beginning functions
Hello, so I am getting into the basics of functions and having a little trouble with my program.
Code:
#include <iostream>
using namespace std;
void func1();
void func2();
void func3(int);
int main ()
{
int choice;
cout << "Input a 1 if you want a party" << endl;
cout << "Input a 2 if you don't want a party\n" << endl;
cout << "Please input your choice now: ";
cin >> choice;
cout << endl;
if (choice == 1)
{
func1();
}
else if (choice == 2)
{
func2();
}
else
{
while (choice != 1 && choice != 2)
{
func3(choice);
{
if (choice == 1)
{
func1();
}
else if (choice == 2)
{
func2();
}
}
}
}
return 0;
}
void func1()
{
cout << "You want a party" << endl;
}
void func2()
{
cout << "You don't want a party" << endl;
}
void func3(int reenter)
{
cout << "Invalid entry. Must enter a 1 or a 2. Re-enter your choice: ";
cin >> reenter;
}
When I enter a number other than 1 or 2 it ask to re-enter like it should but then no matter what number I enter (even a 1 or 2) it just keeps asking me to re-enter a number.
What is wrong that this keeps happening?
-
the argument for func3 is passed by value so changing it inside func3 wouldn't change the value of choice. What you need is passing by reference.
Code:
void func3(int & reenter )
{
cout << "Invalid entry. Must enter a 1 or a 2. Re-enter your choice: ";
cin >> reenter;
}
-
Code:
while (choice != 1 && choice != 2)
{
choice = func3(choice);
{
if (choice == 1)
{
func1();
}
else if (choice == 2)
{
func2();
}
}
}
void func3 (int reenter)
{
cout << "Invalid entry. Must enter a 1 or a 2. Re-enter your choice: ";
cin >> reenter;
return reenter;
}
This is like the minimum fix you can do, though there is a simpler/nicer way, but just for you to understand what is happening.
With blue is the correction, with red is code that should be omitted (not used).
When you do cin >> reenter, you put in the variable "reenter" the value of the input.
You need to give that value also on the main program, you can do so by returning is value.
EDIT: Second options is passing by reference, as above, but there is a "*" missing
Code:
void func3(int & reenter )
{
cout << "Invalid entry. Must enter a 1 or a 2. Re-enter your choice: ";
cin >> *reenter;
}