I have this working code:
/* Include files */
#include <iostream>
#include <string>
#include <limits>
using namespace std;
void fnMainMenu(char s);
/******************************************************************************
* Function: fnUpdateSalary
* Description: Update employee salary
******************************************************************************/
void fnUpdateSalary()
{
int choice = 0;
char data = 'a';
incorrect_input: // goto teleport exit :)
cout<<"\n\t=======================";
cout<<"\n\tWelcome\n";
cout<<"\t=======================\n\n";
cout<<"1. Update employee salary\n";
cout<<"2. Main menu\n";
cout<<"3. Exit system\n";
cout<<"\n >> ";
cin>>choice;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
switch(choice){
case 1 :
//fnUpdateSalary();
break;
case 2 :
fnMainMenu(data);
break;
case 3 :
exit(1);
break;
default :
cout<<"Input not recognized. Please enter the correct input.\n";
}
}
void fnLog()
{
char data = 'b';
fnMainMenu(data); // call Main Menu and I want to pass "hello"
}
/******************************************************************************
* Function: fnMainMenu
* Description: Menu for the customer
******************************************************************************/
void fnMainMenu(char s)
{
cout << s;
if (s == 'a')
{ cout << "a = admin";
}
else
{cout << "\n\nb not admin";
}
//system("cls");
int chooice = 0;
cout<<"\n\t=======================";
cout<<"\n\tWelcome\n";
cout<<"\t=======================\n\n";
cout<<"1. Manage employee\n";
cout<<"2. Search employee\n";
cout<<"3. Employee report\n";
cout<<"4. Reset password\n";
cout<<"5. Exit system\n";
cout<<"\n >> ";
int numbers = 2;
cin>>chooice;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
switch(chooice){
case 1 :
fnUpdateSalary();
break;
case 4 :
// fnChangePassword();
break;
default : exit(1);
}
}
/******************************************************************************
* Function: main
* Description: The main calling function
******************************************************************************/
int main()
{
fnLog();
return 0;
}
fnLog() send b to fnMainMenu(). When I am at fnUpdateSalary() I want to go to fnMainMenu() again. My question is, is there anyway from fnUpdateSalary() or whatever function available to call fnMainMenu() without declaring variable data again? I was hoping I could just use fnMainMenu(); instead of
char data = 'r'; fnMainMenu(data);
I get this error error C2660: 'fnMainMenu' : function does not take 0 arguments if I just called fnMainMenu();
I hope my question make sense. Thanks in advance.
The parameter doesn’t seem to serve a real purpose anyway. Passing b into the main menu function certainly achieves nothing. If you just want to distinguish between admin and non-admin access, change the type and usage of the argument:
void fnMainMenu(bool is_admin) {
if (is_admin)
cout << "Admin\n";
else
cout << "Not admin\n";
}
And call it like this:
fnMainMenu(true);
// Or, alternatively:
fnMainMenu(false);
That’s it. Incidentally, you don’t need (and shouldn’t!) declare a variable to pass as the argument here. Just pass the value directly, like I’ve done above.
Also, why are your function names prefixed by fn? Don’t do this, it’s not good practice. Just use proper names that explain well what the functions do.
If I fully understand what you are doing, you need a combination of two things. Firstly, a static variable in fnMainMenu and secondly a default parameter:
fnMainMenu(char s = '\0')
{
static char c;
if(s != '\0') c = s;
...
...
}
The "static" keyword means that the character will be preserved across function calls. The default parameter means that s will be assigned a null termination character unless you explicitly pass another value.
Since you're writing C++ code and data seems to be relatively long-lived with respect to the application logic, it would perhaps make sense to regroup these functions into a class.
data could be a data member of this class, and fnUpdateSalary, fnLog, fnMainMenu methods.
class Application {
public:
Application ()
: data ('b') // default value
{ }
void fnLog() {
data = 'b';
fnMainMenu ();
}
void fnMainMenu() {
if (data == 'a')
cout << "a = admin";
else
cout << "\n\nb not admin";
// ...
fnUpdateSalary ();
// ...
}
void fnUpdateSalary() {
// ...
fnMainMenu ();
// ...
}
private:
char data;
};
int main () {
Application app;
app.fnLog ();
}
Related
I am learning c++ and I can't wrap my head around this problem. I have created a class object which hold information of a vehicle. And the class name is vehicle. Here is the class:
class vehicle {
private:
string vehicleNumber;
int vehicleType;
public:
//Default Constructor
vehicle();
//Overload Constructor - #params<vehicleNumber, vehicleType>
vehicle(string vehicleNo, int type){
vehicleNumber = vehicleNo;
vehicleType = type;
}
//Some stuff to test
string getNo(){
return vehicleNumber;
}
int getType(){
return vehicleType;
}
};
And now in my main I have a void method which then takes in user input and puts the object in a vector. So in my main:
//Ref
void storeVehicle(vector<vehicle>&);
void storeVehicle(vector<vehicle>& createNewVehicle){
string number;
int type;
cout << "Enter Vehicle Number: ";
cin >> number;
cout << "Enter the vehicle type: ";
cin >> type;
vehicle newV(number, type);
createNewVehicle.push_back(newV);
cout << endl;
}
//
Now here is the problem I am facing. Inside of my main method, I am creating the object. And this works perfectly find except if I call the main method again, it initializes the object again and I loose my previous data. I am not sure how to tackle this.
Here is the main method:
int main(){
vector<vehicle> newVehicle;
storeVehicle(newVehicle);
return main();
}
So here I am returning main() again so that it reruns. But when it does, i loose my previous vector which held the data. Now how can I keep the data and keep calling the storeVehicle method?
Edit
I also have a switch case which I am using to determine what the user chooses as an option. It may be to display the vehicle information or it maybe to add a new vehicle. In this case too, how can I add the vehicle without loosing previous data. Here is my switch which is inside another method:
void mainMenu(){
int option;
cin >> option;
switch(option){
case 1: {
vector<vehicle> newVehicle;
storeVehicle(newVehicle);
break;
}
default:
cout << "Wrong option";
}
}
So now in my main method, I am simply calling this switch method. Either way, I loose the data yes?
EDIT
I don't understand why people keep downvoting. Aren't we all here to learn? And yet I get a downvote. Sooner or later, stackoverflow decides to block me from asking questions.
Main isn't intended to be used like that, it's just an entry point for your application.
For what you're looking to do, you would be interested in looping. This way a certain section of your code can be ran repeatedly until a condition is met.
int main(){
vector<vehicle> newVehicle;
while(true)
{
storeVehicle(newVehicle);
}
return 0;
}
Take a look at how different loop types work. https://www.tutorialspoint.com/cplusplus/cpp_loop_types.htm
Also, the one in my example is an infinite loop, since the condition is always true.
EDIT The question was changed.
The problem is that each time you call the mainMenu function that the vector is recreated. Create the vector in your Main function and then pass it by ref into the mainMenu function, so that it can then be passed into your storeVehicle function.
int main()
{
vector<vehicle> newVehicle;
while (true)
{
mainMenu(newVehicle);
}
return 0;
}
void mainMenu(vector<vehicle>& createNewVehicle) {
int option;
cin >> option;
switch (option) {
case 1: {
storeVehicle(createNewVehicle);
break;
}
default:
cout << "Wrong option";
}
}
You'd have to add a header for this function to work.
#include <limits>
void storeVehicle(vector<vehicle>& createNewVehicle) {
string number;
int type;
cout << "Enter Vehicle Number: ";
cin >> number;
cout << "Enter the vehicle type: ";
cin >> type;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
vehicle newV(number, type);
createNewVehicle.push_back(newV);
cout << endl;
}
I have these functions:
read(){
}
write(){
}
main(){
cout << "This is a menu so you can choose what to do";
}
Its actualy more complicated than that but that example will do fine for you to help me.
I just want to be able to for example write, then go back to the menu, then choose to read etc
I cant do :
read(){
main();
}
main(){
read();
}
because main was not declared before read, so then I move main above read and read was not declared before main.
Exactly this program is an agenda, so that I can creat schedules and manage events (write) and just see my calendar with all the events or just see my schedules (read). I want to be able to go from main to read, then to main again then to write you know
I think I could separate these functions into different files but I dont know how to call a function from another file.
Any help?
Here's another alternative:
int main(void)
{
bool call_read = true;
while (true)
{
if (call_read)
{
read();
}
else
{
write();
}
call_read = !call_read;
}
return 0;
}
In the above example, a bool variable is used to alternate between the read and write functions.
A nice feature of this method is that the functions called don't need to know about each other.
ok, calling main is not a good idea, but I guess the question is more about how having 2 functions calling each other.
you need to forward declare at least one:
int write(); //forward declare
int read() {
return write(); // use write which is still forward declared for now
}
int write() { // now defining write
return read();
}
obviously this sample code is meaning less (infinite loop), but it illustrates how to do that.
A good way to write menus is to use a while loop in main and a switch statement. Assuming the read and write functions do not branch somewhere else, when they complete, they return to their caller, main(). The while loop ensures that the menu does not end until the user is done.
int main()
{
char choice = '\n';
while (choice != 'q')
{
// Display menu options
cout << "r: Read" << endl << "w: Write" << endl << "Enter a choice: ";
cin >> choice;
// Implement menu interface
switch (choice)
{
case 'r':
read();
break;
case 'w':
write();
break;
case 'q':
cout << "Quitting the menu. Bye!" << endl;
break;
default:
cout << "Invalid choice!" << endl;
break;
} //end switch
} // end while
return 0;
} // end main
#include "stdafx.h"
#include <iostream>
#include <string>
int isVowel(char &a, int &counter);
bool enterAnotherOne();
void outputResult(int &counter);
bool goAgain();
using namespace std;
int main() {
int counter = 0;
char a;
do
{
do
{
void enter(a);
int isVowel(counter);
void outputResult();
} while (enterAnotherOne());
} while (goAgain());
return 0;
}// Function main()
// ===================
void enter() {
char a;
cout << "Enter a letter. ";
cin >> a;
}
}// Function Letter()
// ===========================
int isVowel(char &a, int &counter) {
counter = 0;
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' || a == 'y')
{
counter++;
}
return counter;
}// isVowel()
// ==============
bool enterAnotherOne() {
char a;
cout << "Would you like to enter another letter? ";
cin >> a;
if (a == 'y')
{
return true;
}
else
{
return false;
}
}
void outputResult(int &counter) {
cout << "The number of vowels that you entered are " << counter << endl;
}// outputResult()
// ===================
bool goAgain() {
char a;
cout << "Would you like to go again? ";
cin >> a;
if (a == 'y')
{
return true;
}
else
{
return false;
}
}
Hey Guys, I was making a program that would count the number of vowels that are entered when inputting random letters. The problem I am having is that, this line:
void enter(a);
it says incomplete type is not allowed and I can't figure out what is wrong with it.
void enter(a);
is likely being seen by the compiler as either
a declaration of enter as a variable of type void and passing a into the void constructor, and void's not a complete type because you can't make a void. void is nothing.
a declaration of function enter that returns void that expects a parameter of type a passed by value. a would be the incomplete type.
I think the first interpretation is more likely.
Anyway, you likely wanted to call
enter(a);
But that won't work because the enter function doesn't take any parameters. Let's look at enter for a moment.
void enter() {
char a;
cout << "Enter a letter. ";
cin >> a;
}
This function unfortunately doesn't do much. it reads a character from the user and promptly throws it away. We probably want to use that character, so
char enter() {
char a;
cout << "Enter a letter. ";
cin >> a;
return a;
}
Now we get a copy of the character returned to the caller. That means
enter(a);
Should look more like
a = enter();
You have similar problems with
int isVowel(counter);
void outputResult();
right below the call to enter.
Unfortunately enter is not visible to main because it is declared after main is declared. I recommend moving the function declaration to above main in the file. You could forward declare enter as you have done with the other functions, but why bother? A forward declaration means you may have two places to change the code if the function changes.
I recommend pulling out your programming textbook and reading the first few chapters to get a better grasp of functions. If you are learning on your own and have no textbook, or if your textbook sucks, The Definitive C++ Book Guide and List may be of use to you.
Side note: There are more than just guys running around here.
This has a few issues with it.
Firstly, you don't seem to prototype the enter function (you don't declare it with the rest of the functions near the top of the code).
Secondly, I think you're trying to call the functions using the code within the do loops, however it's not clear due to the fact that you've put a type before your reference to the functions. If you're trying to call them, you shouldn't mention any types beforehand, so void enter(a); should just become enter(a); (not really, due to the "a", more on that on the next point).
Thirdly, assuming that you were trying to call the functions in that bit of code, as I assumed above, the arguments you're passing in aren't consistent with the way the functions are defined. For example, enter requires no arguments in the function you've created, however when you attempt to call it in the do loop, you're trying to pass in a variable "a" which it isn't prepared for. Checking the other function calls in that block, you'll find it to be inconsistent with those, too.
Fourthly, and building off of the last point, I believe you made the mistake of leaving out the "a" variable being passed into enter, as you reference it whilst within the function however it is never passed in.
Don't be discouraged by this! Keep learning and prosper!
There's quite a few issues with your code, I've put some meaningful comments in my code to help you. It sounds harsh, but I'm must in a rush, so I'm not trying to be. This will fully compile and run like I think you'd like.
#include "stdafx.h"
#include <iostream>
#include <string>
void enter(char&); /*You forget to put the function prototype here.*/
void isVowel(char &, int &); /*Since you are passing by reference, and NOT using the return value, you don't need have have it return int.*/
bool enterAnotherOne();
void outputResult(int &);
bool goAgain();
using namespace std;
int main() {
int counter = 0;
char a;
do
{
do
{
enter(a); //you don't need to declare the function type when calling a function :(
isVowel(a, counter); /*You didn't properly pass the argument here*/
outputResult(counter); //This needs an argument.
} while (enterAnotherOne());
//Did you want to reset the counter? if so, do it here.
counter = 0;
} while (goAgain());
return 0;
}// END OF Function main() /*Make sure you clarify it is the END OF function main().*/
// ===================
void enter(char &letter) { /*This requires an argument to be useful.*/
cout << "Enter a letter. ";
cin >> letter;
}
// END OF Function Letter() also, you had an extra bracket, which means this wouldn't compile.
// ===========================
void isVowel(char &a, int &num) {
//counter = 0; //if your're coing to pass counter as a argument, why doe this?
//counter = 0 resets counter back to 0.
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' || a == 'y')
{
num++;
}
}// END OF isVowel()
// ==============
bool enterAnotherOne() {
char choice; //give meaningful variable names!
cout << "Would you like to enter another letter? ";
cin >> choice;
if (choice == 'y')
{
return true;
}
else
{
return false;
}
}//If you're going ot comment END OF on every function, might as well do it here.
void outputResult(int &num) {
cout << "The number of vowels that you entered are " << num << endl;
}// END OF outputResult()
// ===================
bool goAgain() {
char choice;
cout << "Would you like to go again? ";
cin >> choice;
if (choice == 'y')
{
return true;
}
else
{
return false;
}
}//where's END OF for this function?
Im trying to lean structures and I think I am doing something wrong when I use the structure and trying to call it into a function.
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
//Structure
struct Inventory
{
int NumberPartsBin;
};
//Function Prototypes.
void choiceMenu();
void AddParts(int &);
void RemoveParts(int &);
int main()
{
char Election;
int choice;
Inventory Parts = {10};
const int Valve_Choice = 1,
Quit_Choice = 2;
I am trying to to resolve this problem with one item, but I will use arrays for 10 items.
do {
choiceMenu();
cin>> choice;
if (choice >= Valve_Choice & choice <= Quit_Choice)
{
switch(choice){
case Valve_Choice:
cout<<"Enter A for Add Parts or R to Romove Parts";
cin >> Election;
if (Election=='A')
{
AddParts(Parts);// My problem is here
}
if else (Election =='R'){
RemoveParts(Parts);}
else{
cout << "Invalid Entry. Try Again";
cin >> Election; }
break;
case Quit_Choice:
cout<<"Program Ending";
return;
else
{
cout<<"Enter a valid choice!!;
cin >> choice;
}
}
}
while (choice >= Valve_Choice & choice < Quit_Choice);
system("pause");
return 0;
// Bin Choice
void choiceMenu()
{
// We use ofstream to create and write on a text file.
ofstream outputFile;
outputFile.open("C:\\Users\\Alexander MR\\Desktop\\CompanyABCPayRoll.txt");
// The headed of the document.
outputFile << " Inventoy\n";
outputFile << " = = = = = = = = \n";
outputFile << " *Choose the part of your preference.\n";
outputFile << " 1. valves = " << Parts.NumberPartsBin << endl;
outputFile << " 11. Choose 2 to quit the Program" << endl;
outputFile.close();
}
I am not sure of my function either.
my function to add parts
void AddParts(int &Parts1)
{
int Enter1;
Parts1.NumberPartsBin = Parts1.NumberPartsBin + Enter1;
}
My function to remove parts
void RemoveParts(int &Parts2)
{
int Enter2;
Parts2.NumberPartsBin = Parts2.NumberPartsBin - Enter2;
}
Reading the question with only parts of the code formatted is quite hard. The first thing I saw was:
void RemoveParts( int &Parts2 ) {
int Enter2;
Parts2.NumberPartsBin = Parts2.NumberPartsBin - Enter2;
}
This makes no sense at all. If Parts2 is an int, then you will never be able to say Parts2.NumberPartsBin. The second thing is int Enter2;. You never give it a value, but in the next line you want to subtract it from something‽
I'm guessing (at least with this function) that you are trying to do something like this:
void RemoveParts( Inventory& inventoryItem, int amountOfParts ) { // inventoryItem is passed by reference, amountOfParts is passed by value
inventoryItem.NumberPartsBin = inventoryItem.NumberPartsBin - amountOfParts;
}
Looking at your code, I'm guessing you're quite new to all of this. I'm no guru, but please:
Capitalize class/struct names and start variable names with a lowercase. ( like parts or election)
If you want to change the value that comes into a function, pass it by reference, but if it is something like an int or a char, simply pass it by value.
p.s. it's if, else if, else and not if else which will otherwise be the next error in your code.
I started learning some basics of C++ and I wanted to write some code to practices what I've learned. I wanted to make a class and some functions. It's supposed to be a title screen to start a text game, except there is no game...yet :P
Whenever I enter 1 to start so it displays "Good Work" it just does nothing after I hit enter.
Any point in the right direction would be great. I've been watching videos and reading tutorials on functions, it doesn't seem to cover the problem I'm having...
#include <iostream>
#include <string>
using namespace std;
//Function Protos
void keyError();
int userInput(int x);
//class library
class Title
{
bool nSelect;
int x;
public:
void titleScreen()
{
while(nSelect)
{
cout << "Welcome to Biggs RPG!" << endl << "1. Play 2. Exit" << endl;
userInput(x);
if (userInput(1))
nSelect = 0;
else if (userInput(2))
{
cout << "Closing program..." <<endl;
nSelect = 0;
}
else
keyError();
}
}
};
int main()
{
Title displayTitle;
displayTitle.titleScreen();
cout << "Good work";
return 0;
}
void keyError()
{
cout << "Meow? Wrong input try again." << endl;
}
int userInput(int x)
{
x = 0;
cin >> x;
return x;
}
There are numerous stylistic and technical problems. Try learning from resources recommended in The Definitive C++ Book Guide and List.
Here is a start…
#include <iostream>
#include <string>
// "using namespace std;" is poor practice. Better to write out std::
/* Unless you will have two title screens at the same time,
this should probably be a namespace, not a "singleton" class. */
namespace Title
{
int nSelect;
void titleScreen()
{
do {
// prompt for input
std::cout << "Welcome to Biggs RPG!\n" "1. Play 2. Exit\n";
// get ready to accept input, even if there was an error before
if ( ! std::cin ) {
std::cin.clear(); // tell iostream we're recovering from an error
std::cin.ignore( 1000, '\n' ); // ignore error-causing input
}
// repeat if invalid input
} while( ! std::cin >> nSelect || ! handleInput( nSelect ) );
The difference is that you want to ask for input, then handle it. The code you posted asks for input again each time it checks what the input was.
This is a do … while loop, so it executes at least once and then repeats as long as the condition at the end is true. If the user gives an invalid input, then ! std::cin evaluates to true. Then the policy of C++ is to stop returning any input until you call std::cin.clear(), which signals that you are going to try again. ignore then gets rid of the invalid input. Then ! std::cin >> nSelect tries to read a number, and if that operation is successful, call handleInput (which you must write) which should return false if the input was invalid. So if reading a number fails, or the wrong number was entered, the loop goes again.
You should compare the return value of userInput with 1 or 2, like this:
int userInput(void);
//class library
class Title
{
bool nSelect;
int x;
public:
void titleScreen()
{
nSelect = true;
while(nSelect)
{
cout << "Welcome to Biggs RPG!" << endl << "1. Play 2. Exit" << endl;
x = userInput();
if (x == 1)
nSelect = false;
else if (x == 2)
{
cout << "Closing program..." <<endl;
nSelect = false;
}
else
keyError();
}
}
};
and define userInput as:
int userInput(void)
{
int x = 0;
cin >> x;
return x;
}
I sense confusion about the difference between parameters and return values. When you define a function as
int userInput(int x) {
...
You pass a value to the function (x) and return a value with the return statement. In your case you don't need to pass a parameter to your function; you need to return a value. You access this value by assigning it to another variable:
theResult = userInput(123);
But it doesn't matter what value you pass to the function; you might as well use
int userInput(void) {
...
In which case you can use
theResult = userInput();
Now just to confuse you, it is possible to pass the address of a variable as a parameter to a function. You can use that either to access data (usually a "larger" block of data like an array or struct) but it can also be used to provide a place where a return value is stored. Thus
void squareMe(int *x){
*x*=*x;
}
Would return the square of the number pointed to in that location. You could then do
int x=4;
squareMe(&x);
cout << x;
Would print out 16 (!). This is because the function looks at the contents of the address (&x is the address of the variable x), and multiplies it by itself in- place.
I hope this explanation helps.